1
votes

I am trying to sort a list<CMail> ( where CMail is some object, not important for purpose of this question ). Now, I'd like to sort it. I am aware that list has a sort() function, which either uses standard operator< etc., or given compare function. And I do have such a function.

my function

bool comp( const CMail & x ) const;

returns, if we do consider a.comp(b); , true if a < b, and false otherwise. This function is also part of CMail class and therefore CMail namespace.

Now, I'd like to use this sorting function, and I'm using

temp.sort( CMail::comp );

where temp is a

list<CMail> temp;

But, compiler doesnt let me, saying

error: invalid use of non-static member function ‘bool CMail::comp(const CMail&) const’

does anyone see where the problem could be? Thanks in advance :)

3

3 Answers

5
votes

The comparison has to be a binary functor that can compare all elements of the list. The member function CMail::comp does not satisfy that. Try a non-member. This can be implemented in terms of your member CMail::comp:

bool comp(const CMail& lhs, const CMail& rhs )
{
  return lhs.comp(rhs);
}

and then

temp.sort(comp);

Alternatively, use a lambda:

temp.sort([](const CMail& lhs, const CMail& rhs ){return lhs.comp(rhs);});
0
votes

Change your comp function to static. You are trying to access it with no object instantiated.

0
votes

The non-member function used as a comparison has to take two arguments and return bool

bool comp( const CMail & x1, const CMail& x2) {
    return 1;
}

int main(int argc, char** argv) {
    std::list<CMail> l;
    l.assign( 4, CMail());
    l.sort( &comp);
}

In C++11 you can use lambda function. Here is example which calls a member function CMail::comp:

int main(int argc, char** argv) {
    std::list<CMail> l;
    l.assign( 4, CMail());
    l.sort( [](const CMail& x1, const CMail& x2) { return x1.comp( x2);});
                                                           ^^^^ //member function
}