Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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

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.

like image 519
Lennart Avatar asked Jun 11 '16 19:06

Lennart


3 Answers

Make your comparator function static. It will work.
like image 188
arpit1714 Avatar answered Oct 13 '22 19:10

arpit1714


To call compare you need a Field object. You could use a lambda a call it from in there if you have C++11 support:

sort(vec.begin(), vec.end(), [this] (vector<int> a, vector<int> b) {
    return compare(a, b); });

Or just move your comparison method out of the class, you don't need to access it's members anyway.

like image 7
Hatted Rooster Avatar answered Oct 13 '22 20:10

Hatted Rooster


There are three ways of doing this :

  1. Create a structure with operator() defined for the structure

    struct compareFunc {

     inline bool operator() (const vector<int> &a, const vector<int> &b)
     {
         return (a.back() < b.back());
     }
    

    };

    and in sort function call in the below fashion:

    std::sort(vect.begin(), vect.end(), compareFunc());

  2. If you are using C++11 version then write your lamda function and call the comparator function defined in your class:

     std::sort(vec.begin(), vec.end(), [this](vector<int> a, vector<int> b){
                 return (compareFun(a,b));
    

    });

    Define compareFun in your class in the below mentioned manner:

    class Test { public: bool compareFun(vector a, vector b) { return (a.back() < b.back()); } };

  3. Using static method as mentioned by one of our friend. I hope this works.

like image 5
Dixit Avatar answered Oct 13 '22 21:10

Dixit