如何根据第一个元素对一对增加进行排序,然后根据第二个元素减少?

时间:2016-03-03 15:25:02

标签: c++

我如何对这样的对进行排序,例如:

输入:

1 99

2 100

1 100

3 400

2 101

输出:

1 100

1 99

2 101

2 100

3 400

1 个答案:

答案 0 :(得分:2)

创建比较器并使用std::sort函数。

struct Comp {
  bool operator()(const std::pair<int, int> &a, const std::pair<int, int> &b) {
    if (a.first != b.first) {
      return a.first < b.first;
    }
    return a.second > b.second;
  }

};

然后创建结构的一个实例并将其传递给std::sort

Comp comp_functor;
std::sort(myVec.begin(), myVec.end(), comp_functor);

要执行此操作,您需要#include <algorithm>。另请注意,std::sort不保证稳定性,因此如果您希望稳定性使用std::stable_sort

相关问题