std::sort function with custom compare function results error: reference to non-static member function must be called

Lennart picture Lennart · Jun 11, 2016 · Viewed 11.2k times · Source

I have trouble using the std::sort function with my custom comparison function when defined inside a class.

class Test {
    private:
        vector< vector<int> > mat;
        bool compare(vector<int>, vector<int>);
    public:
        void sortMatrix();
}

bool Test::compare( vector<int> a, vector<int> b) {
    return (a.back() < b.back());
}

void Test::sortMatrix() {
    sort(vec.begin(), vec.end(), compare);
}

I get the following error message:

error: reference to non-static member function must be called
        sort(vec.begin(), vec.end(), compare);
                                     ^~~~~~~

When I however define compare() and sortMatrix() in the file main.cpp without any class, everything works fine. I would appreciate any help and suggestions.

Answer

arpit1714 picture arpit1714 · May 2, 2020
Make your comparator function static. It will work.