我知道已经有关于它的问题,并且我遵循了所有提示,但它仍然不起作用,所以我很高兴知道出了什么问题。
我有这个结构:
struct Scores
{
int _score;
std::string _name;
};
我想按 _score 从高到低对 vector 进行排序。这是我写的:
std::sort (_scores.begin(), _scores.end(), myFunction);
我有这个功能:
bool myFunction (const struct Scores &i, const struct Scores &j)
{return i._score>j._score;}
我已经包含了算法,所以我真的不知道是什么问题。我收到这些错误:
error C3867: 'HighScores::myFunction': function call missing argument list;
error C2780: 'void std::sort(_RanIt,_RanIt)' : expects 2 arguments - 3 provided
谢谢
最佳答案
看起来你的例子中的 myFunction 是成员类函数。它必须是静态的,然后才能成为 std::sort
算法的正确谓词。或者,您可以将此函数设为免费的优秀函数。
或者你可以做一个仿函数
struct Sorter {
bool operator ()( const Scores &o1, const Scores &o2) {
return o1._score > o2._score;
}
};
并将其实例传递给算法:
std::sort ( _scores.begin(), _scores.end(), Sorter());
关于c++ - 使用 <algorithm> 对结构 vector 进行排序,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/24232047/