对包含 pair<x,y> 的向量进行排序
Sorting a vector that contains pair<x,y>
我在某个地方看到过一段代码,其中有人做了类似的事情
#define pp pair<int,int>
int main()
{
int n,i;
scanf("%d",&n);
vector<pp> G;
for(i=0;i<n;i++)
{
int x,y;
scanf("%d%d",&x,&y);
G.push_back(pp(x+y,x-y));
}
sort(G.begin(),G.end());
我想知道这里是如何排序的。我的意思是说在包含对的向量中执行什么参数排序。
检查此 link:http://www.cplusplus.com/reference/utility/pair/operators/
Similarly, operators <, >, <= and >= perform a lexicographical comparison on the sequence formed by members first and second.
因此,a < b
表示 (a.first < b.first) || (a.first == b.first && a.second < b.second)
sort
函数根据比较函数(定义顺序)进行排序。人们可能想要指定要使用的比较函数,但是如果未指定比较函数(如您的情况),则 sort
使用默认顺序作为所考虑对象上的 <
运算符
所以在你的情况下,排序是可能的,因为比较运算符为 std::pair
.
超载了
此处描述了这些运算符的行为:http://en.cppreference.com/w/cpp/utility/pair/operator_cmp
因此,在对 std::pair
class 进行排序时,将调用 <
运算符,并且您的对将按字典顺序排列
(0,1) < (0,2) < (1,0) < (1,2) < (2,7)
我在某个地方看到过一段代码,其中有人做了类似的事情
#define pp pair<int,int>
int main()
{
int n,i;
scanf("%d",&n);
vector<pp> G;
for(i=0;i<n;i++)
{
int x,y;
scanf("%d%d",&x,&y);
G.push_back(pp(x+y,x-y));
}
sort(G.begin(),G.end());
我想知道这里是如何排序的。我的意思是说在包含对的向量中执行什么参数排序。
检查此 link:http://www.cplusplus.com/reference/utility/pair/operators/
Similarly, operators <, >, <= and >= perform a lexicographical comparison on the sequence formed by members first and second.
因此,a < b
表示 (a.first < b.first) || (a.first == b.first && a.second < b.second)
sort
函数根据比较函数(定义顺序)进行排序。人们可能想要指定要使用的比较函数,但是如果未指定比较函数(如您的情况),则 sort
使用默认顺序作为所考虑对象上的 <
运算符
所以在你的情况下,排序是可能的,因为比较运算符为 std::pair
.
此处描述了这些运算符的行为:http://en.cppreference.com/w/cpp/utility/pair/operator_cmp
因此,在对 std::pair
class 进行排序时,将调用 <
运算符,并且您的对将按字典顺序排列
(0,1) < (0,2) < (1,0) < (1,2) < (2,7)