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

How do i sort a pair increasing based on first element then decreasing based on second element?

本文关键字:元素 排序 第二个 然后 何根 第一个 增加      更新时间:2023-10-16

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

输入:

1 99

2 100

1 100

3 400

2 101

输出:

1 100

1 99

2 101

2 100

3 400

创建一个比较器并使用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

相关文章: