c++ - 根据特定字段对结构 vector 进行排序

标签 c++ sorting

目前我正在尝试根据特定字段对结构 vector 进行排序。我已经为排序功能的使用设置了自定义比较功能。但是,我遇到了一些错误。

代码:

    struct Play{
      int min, down, yard, locat;
      string Description, offname, defname;
      double relevance;
     };

    bool customCompare(const Play &x, const Play &y)
    {
        return (x.relevance < y.relevance);
    }

    void printResults()
    {
        sort(vecData.begin(),vecData.end(), customCompare);
    }`

错误:

    error C3867: 'List::customCompare': function call missing argument list; use '&List::customCompare' to create a pointer to member
    error C2780: 'void std::sort(_RanIt,_RanIt)' : expects 2 arguments - 3 provided

最佳答案

a) 使用带有 lambda 表示法的排序函数,如下所示(如果您使用的是 c++11)

 sort(vecData.begin(),vecData.end(), [](const Play &x, const Play &y){ return (x.relevance < y.relevance);});

工作代码:

http://ideone.com/bDOrBV

b) 使比较器函数为静态

http://ideone.com/0HsaaH

关于c++ - 根据特定字段对结构 vector 进行排序,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/20167035/

相关文章:

c++ - 矩阵中字符的随机移动

c++ - 轮廓和矩形 OPENcv c++ 之间的交集

java - 数组排序方法行为

javascript - knockout JS : Sorting and splicing an observable array of observable numbers

c - mergesort : no errors and warnings when compile and link, 但输出不按顺序

C# LINQ Orderby - 真/假如何影响 orderby?

c++ - 可以在尾随返回类型语法中直接使用参数值(不是它的类型而是值本身)

c++ - 无法直接将QImage添加到QGridLayout

c++ - Yacc 语法产生不正确的终端

Linux 使用 'nested' 字段排序