Reputation: 376
I wrote myself a compare function for sort(). It worked well when I put it this way.
bool comp(string a, string b)
{
...;
}
int main()
{
sort(...,...,comp);
}
However, when I put all this inside a class, say:
class Test {
public:
bool comp(string a,string b)
{
...;
}
vector <string> CustomSort(vector <string> str) {
sort(...,...,comp);
}
};
There is a compile error "No matching function for call to 'sort ......'.
Why would this happen?
Upvotes: 2
Views: 1348
Reputation: 133122
Any nonstatic member function of class X
has an extra argument - a reference/pointer to (const
) X
which becomes this
. Therefore a member function's signature isn't such that can be digested by sort
. You need to use boost::bind
or std::mem_fun
or std::mem_fun_ref
. When using C++11, you can use std::bind
.
std::sort(..., ..., std::bind(&Test::comp, this, _1, _2));
Come to think of it, the best solution in this case would be to make your comp function static, because it doesn't need this
at all. In this case your original code will work without change.
Upvotes: 6