【问题标题】:Sorting a vector in descending order c++ [duplicate]按降序对向量进行排序c ++ [重复]
【发布时间】:2018-10-08 16:54:09
【问题描述】:

我正在尝试按学生的平均分对向量进行降序排序,但我不知道正确的方法是什么? .现在是我的代码了。

          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]);
               }
             }
        } 

       }

【问题讨论】:

  • 您实际上是指std::map - 因为这个问题对此没有任何意义 - 还是std::vector
  • 我编辑它,它是一个向量
  • 现在您已将其更改为矢量,使用std::sort,而不是可怕的冒泡排序。
  • 如果你在谷歌搜索中复制粘贴你的问题的确切标题,它会提供几个非常好的答案...

标签: c++ sorting dictionary iterator


【解决方案1】:

像这样使用std::sortstd::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;});
//...

【讨论】:

  • 谢谢,但我已经通过了,更大的未定义,我应该创造更大的打击吗?
  • @Joe add #include
  • 错误 2 错误 C2664: 'bool std::greater::operator ()(const _Ty &,const _Ty &) const' : 无法将参数 1 从 'CStudent' 转换为 'const int &' c:\program files (x86)\microsoft visual studio 12.0\vc\include\algorithm 3071 1 Project1
  • @Joe:您不是在对整数进行排序,而是在对自己的struct 进行排序。见Sorting a vector of custom objects
  • @Joe 因为你有 CStudent 的容器,你需要在这个类中覆盖 operator>
猜你喜欢
  • 2012-02-19
  • 1970-01-01
  • 1970-01-01
  • 2019-11-04
  • 2022-01-02
  • 2022-07-20
  • 2013-10-15
  • 2022-11-28
  • 2011-11-16
相关资源
最近更新 更多