im trying to use a sort function to sort a list i have containing pairs comparing their second value. this is what i am using:
std::sort(score_list.begin(), score_list.end(), compare_pair);
This is the sort function:
bool Highscore::compare_pair (std::pair<std::string, int> first, std::pair<std::string, int> second)
{
if (first.second<second.second) return true;
else return false;
}
and i am getting this error message:
error: no matching function for call to ‘sort(std::list<std::pair<std::basic_string<char>, int> >::iterator, std::list<std::pair<std::basic_string<char>, int> >::iterator, <unresolved overloaded function type>)’
Any advice? Thanks
You can’t pass a member function directly as the comparator. When you use a function, what’s actually passed is a pointer to the function — but a pointer to a function is entirely different from a pointer to a member function.
C++98/03 has a couple of adapters named
mem_funandmem_fun_refthat (sort of) deal with this.C++11 adds
mem_fnand deprecatesmem_funandmem_fun_ref. It’s quite a bit easier to use, assuming you have a compiler new enough to include it.If your compiler is that new, however, it’ll probably also include lambdas, which can make the task considerably cleaner, because you can us an “in place” definition of a function object to handle the comparison:
If you Google for something like “C++11 lambda” you should find quite a bit more information about this (much of which will almost certainly lead directly back here to SO).