如何根据第一个元素对增加然后根据第二个元素减少对进行排序
How do i sort a pair increasing based on first element then decreasing based on second element?
例如,我如何对这样的对进行排序:
输入:
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
。
相关文章:
- 查找两个排序向量中共有的元素
- C++ 如何比较n个排序的整数向量以找到互元素?
- 如何在 c++ 中根据第二个元素按降序对列表进行排序
- 对的排序向量 (std::vector<pair<int, int>>) 按对的第一个元素搜索并更新第二个元素值
- 高级选择排序 - 在一次迭代中搜索两个元素
- 为什么用户定义的函数不按照给定的顺序对相同长度的元素进行排序?
- 为什么这个选择排序算法仍然切换一个元素,当它已经是其他元素中最小的元素时?
- 快速排序 - 三个中位数枢轴选择 - 某些元素顺序不正确
- 将一系列已排序的元素划分为相邻组
- 如何通过保持第一个插入的位置来对列表中插入的其余元素进行排序?
- 保持排序的数据结构,允许log N插入时间,并且可以返回我在log N中查找的元素的索引
- "x"的所有元素都存在于"y"(排序向量)中吗?
- 如何根据对的第二个元素对 STL c++ 中的一组对进行排序?
- 如何在保持它们连接到同一元素的同时对 2 个数组进行排序?
- 使用 pair 创建priority_queue,以便在第一个元素相等时"<"第一个元素的排序,对第二个元素">"排序
- 如何将元素排序到矩阵C++
- 如何保持按第二个元素排序的对的优先级队列?
- 如何从两个数组中生成一对向量,然后使用CUDA/Thrust按对的第一个元素排序
- 部分排序数组,最后n个元素排序
- 如何对一对向量按降序排序,并按第二个元素排序