我正在尝试使用排序函数对包含比较其第二个值的对的列表进行排序。这就是我正在使用的:
std::sort(score_list.begin(), score_list.end(), compare_pair);
这是排序函数:
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;
}
我收到此错误消息:
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>)’
有什么建议吗?谢谢
最佳答案
您不能直接将成员函数作为比较器传递。当您使用函数时,实际传递的是指向函数的指针——但指向函数的指针完全不同于指向成员函数的指针。 p>
C++98/03 有一对名为 mem_fun
和 mem_fun_ref
的适配器(在某种程度上)处理这个问题。
C++11 添加了 mem_fn
并弃用了 mem_fun
和 mem_fun_ref
。假设您有一个足够新的编译器来包含它,它就更容易使用。
但是,如果您的编译器是那么新,它可能还会包含 lambda,这可以使任务更加清晰,因为您可以使用函数对象的“就地”定义来处理比较:
typedef std::pair<std::string, int> data_t;
std::sort(score_list.begin(), score_list.end(),
[](data_t const &a, data_t const &b) {
return a.second < b.second;
});
如果你用谷歌搜索“C++11 lambda”之类的东西,你应该会找到更多关于它的信息(其中大部分信息几乎肯定会直接回到 SO)。
关于c++ - 使用排序函数根据函数对列表进行排序,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/13851980/