c++ - 使用 <algorithm> 对结构 vector 进行排序

标签 c++ algorithm sorting vector struct

我知道已经有关于它的问题,并且我遵循了所有提示,但它仍然不起作用,所以我很高兴知道出了什么问题。

我有这个结构:

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/

相关文章:

c++ - 在 ribbon mfc 中显示消息栏

c++ - 为我的链表实现一个迭代器类。 using关键字是什么?

c++ - 编译器如何区分 C++ 中的私有(private)数据和公共(public)数据?

c++ - std::string 的转换运算符无法处理赋值

c++ - 如何创建自解压存档(以编程方式)

algorithm - 为什么深度优先搜索声称具有空间效率?

Java - 包含整数列表的 TreeSet?

java - 神经网络反向传播算法卡在异或训练模式上

python - 使用 for 循环对列表中的数字进行排序

arrays - 从排序数组中选择项目<值的有效方法