按降序对矢量进行排序c ++ [重复]

问题描述 投票:0回答:1

这个问题在这里已有答案:

我试图按照学生的平均分数降序排序矢量,但我不知道这样做的正确方法是什么? 。现在是我的代码。

          void sortDes()
       {
       int len = students.size();
       for(int i = 0; i < len; i++)
       {
            for(int j = 0;j < len - 1; j++)
            {
              if(students[j].average()> students[j+1].average())
               {

                swap(students[j+1], students[j]);
               }
             }
        } 

       }
c++ sorting dictionary iterator
1个回答
1
投票

std::sort一样使用std::greater

#include <functional>
#include <vector>
#include <algorithm>
int main()
{
    std::vector<int> Vec {2,5,4,8,1,2,2};
    std::sort(Vec.begin(), Vec.end(), std::greater<int>());// After sort will be 8,5,4,2,2,2,1
    return 0;
}

在你的情况下,它将是:

std::sort(students.begin(), students.end(), std::greater<int>());

对于您的CStudent覆盖运算符>如下所示:

class CStudent
{
public:
    bool operator > (CStudent& cmp1)
    {
        //Do your own calculations here
        if ( cmp1.val < val )
        {
            return true;
        }

        return false;
    }
private:
    int val;
};

然后用lambda调用sort:

//...
    std::sort(Vec.begin(), Vec.end(), [](CStudent& cmp1, CStudent& cmp2  )->bool{return cmp1 > cmp2;});
//...
© www.soinside.com 2019 - 2024. All rights reserved.