对包含对的向量进行排序(Sorting a vector that contains pair)

编程入门 行业动态 更新时间:2024-10-15 10:15:56
对包含对向量进行排序(Sorting a vector that contains pair)

我见过一个代码,其中一个人做了类似的事情

#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());

我想知道如何在这里完成排序。 我的意思是说在包含对的向量中执行什么参数排序

I have seen a code somewhere in which a guy did something like this

#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());

I want to know how sorting is done here. I mean to say on what parameter sorting is performed in a vector that contains pairs in it.

最满意答案

sort函数根据comparaison函数(定义顺序)进行排序。 可能想要指定使用哪个omparaison,但是如果未指定comparaison函数(如在您的情况下),则sort使用defaut顺序作为被认为对象的< operator

因此,在您的情况下,可以进行排序,因为comparaison运算符为std::pair重载。

这里描述了这些运营商的行为: http : //en.cppreference.com/w/cpp/utility/pair/operator_cmp

因此,当调用std::pair类的< operator时,将调用你的对,并按字典顺序排序

(0,1) < (0,2) < (1,0) < (1,2) < (2,7)

The sort function sort according to an comparaison function (which defines the order). One could want to specify which omparaison to use, however if the comparaison function is not specified (like in your case) then sort uses the defaut order being the < operator on the considered object

So in your case, ordering is possible because the comparaison operator is overloaded for std::pair.

The behaviour of those operator is described here : http://en.cppreference.com/w/cpp/utility/pair/operator_cmp

Therefor, when sorting the < operator on the std::pair class will be called, and your pairs are going to be ordered lexicographically

(0,1) < (0,2) < (1,0) < (1,2) < (2,7)

更多推荐

本文发布于:2023-08-03 11:36:00,感谢您对本站的认可!
本文链接:https://www.elefans.com/category/jswz/34/1387009.html
版权声明:本站内容均来自互联网,仅供演示用,请勿用于商业和其他非法用途。如果侵犯了您的权益请与我们联系,我们将在24小时内删除。
本文标签:向量   Sorting   pair   vector

发布评论

评论列表 (有 0 条评论)
草根站长

>www.elefans.com

编程频道|电子爱好者 - 技术资讯及电子产品介绍!