对对向量进行排序 <int,int>
Sorting a vector of pairs <int,int>
如何在STL中使用std::sort()在STL中使用incr <int,int>
时按降序排序一对向量?它应该先对第一个元素排序,然后对第二个元素排序。
operator<
对于pair<int,int>
是重载的,因此您可以像任何其他向量一样对一对向量进行排序。如果您需要降序排序,您有两个选择—排序,然后调用std::reverse
来反转结果,或者为排序提供谓词。
你也可以使用std::greater
:
#include <iostream>
#include <vector>
#include <algorithm>
using namespace std;
int main() {
vector<pair<int, int> > a;
a.push_back(make_pair(1, 2));
a.push_back(make_pair(2, 3));
sort(a.begin(), a.end(), greater<pair<int,int> >());
return 0;
}
use this,
template<class T>
struct sortFunctor: public unary_function<std::pair<int, int>, std::pair<int, int>>
{
bool operator()(const std::pair<int, int>& First, const std::pair<int, int>& Second)
{
if(First.first < Second.first)
{
return false;
}
if(First.first == Second.first && First.second < Second.second)
{
return false;
}
return true;
}
}
然后将此函子作为第三个形参传递给sort函数。
相关文章:
- 为什么在全局范围内使用"extern int a"似乎不行?
- int(c) 和 c-'0' 之间的区别。C++
- 从"int*"强制转换为"unsigned int"会丢失精度错误
- 为什么野牛仍在使用"int yylex(void)",却找不到"int yylex(YYS
- 有符号的int和int-有没有一种方法可以在C++中区分它们
- 请解释这句话(cout<<1+int((a<b)^((b-a)&1) )<<endl
- 是否可以从int转换为enum类类型
- 不能在初始值设定项列表中将非常量表达式从类型 'int' 缩小到'unsigned long long'
- 向量 <int> a {N, 0} 和 int arr a[N] = {0} 的时间复杂度有什么区别
- 'short int'持有的值溢出,但"自动"不会溢出?
- 如何在C++中将一个无符号的 int 转换为两个无符号的短裤?
- 调用'begin(int [n])'没有匹配函数
- 没有显式声明的int[]中的foreach
- 在c++中访问int到类对象的映射时出错
- 为什么我无法更改"set<set>"循环中的值<int>
- EASTL矢量<向量<int>>连续的
- 为什么将此对向量&lt; map&lt; int,int&gt;&gt;中的地图进行更新.失败
- 如何加入向量&lt; int&gt;到C 中的单个INT
- 是numeric_limits&lt; int&gt; :: is_modulo从逻辑上矛盾
- 'structstd::对<int,int>'没有名为'push_back'