kino92
kino92

Reputation: 39

Using custom compare function for list sort within a class

There seems to be an issue with using a member function when i want to create a custom compare for the std::list function sort. I'm getting the following errors:

Error C3867 'my_class::cmp': non - standard syntax; use '&' to create a pointer to member
Error C2660 'std::list>::sort': function does not take 1 arguments

Below is the code to reproduce the error

#include <list>

class my_class {
    std::list<int> container;
public:
    bool cmp(const int& a, const int& b) {
        return a < b;
    }

    void push(int e) {
        container.push_back(e);
        container.sort(cmp);
    }
};


int main()
{

    my_class my_c;
    return 0;
}

Not really sure why im getting the errors. If i do this outside a class it works just fine.

Upvotes: 0

Views: 593

Answers (1)

Evg
Evg

Reputation: 26362

C++ reference reads:

comp - comparison function object ... . The signature of the comparison function should be equivalent to the following:

bool cmp(const Type1 &a, const Type2 &b);

Your cmp() is a member function and doesn't have this signature. Loosely speaking, it takes three arguments, not two, the first one being an object (*this).

To make .sort() happy, make cmp() a static member function:

static bool cmp(const int& a, const int& b) {
    return a < b;
}

Static member functions do not need objects to be called. So, it has the desired signature, and your code should compile.

If you want to use a non-static member function as a comparator, the easiest way is to use a lambda:

container.sort([this](const int& a, const int& b) { return cmp(a, b); });

Note how we explicitly capture this pointer that will then be used (implicitly) to invoke cmp.

Instead of const int& you can use just int. It has small size and there is no sense to pass it by reference.

Upvotes: 1

Related Questions