简体   繁体   English

在C ++中使用向量对进行排序

[英]sorting using vector pair in c++

I am using vector pair to sort where I am inserting first and second element using a loop 我正在使用向量对对要使用循环插入第一个和第二个元素的位置进行排序

vect.push_back(make_pair(count[i],arr[i]));

sort(vect.begin(),vect.end());

cout<<vect[i].second<<" ";

if my counts are equal then I want to print the second element in the order they were inserted in vector, 如果我的计数相等,那么我想按它们在矢量中插入的顺序打印第二个元素,

but it is not happening. 但它没有发生。

Can someome tell me why? 有人可以告诉我为什么吗?

From std::sort 来自std::sort

Sorts the elements in the range [first, last) in ascending order. 按升序对[first,last)范围内的元素进行排序。 The order of equal elements is not guaranteed to be preserved. 相等元素的顺序不能保证得到保留。
1) Elements are compared using operator<. 1)使用operator <比较元素。

and from std::pair::operator< 并从std::pair::operator<

3) If lhs.first < rhs.first, returns true. 3)如果lhs.first <rhs.first,则返回true。 Otherwise, if rhs.first < lhs.first, returns false. 否则,如果rhs.first <lhs.first,则返回false。 Otherwise, if lhs.second < rhs.second, returns true. 否则,如果lhs.second <rhs.second,则返回true。 Otherwise, returns false. 否则,返回false。

So effectively, sort compares count[i] , and if two of them are equal, it compares arr[i] . 如此有效地,sort比较count[i] ,如果两个相等,则比较arr[i]


If you want to compare the count s only and keep the original order for equal keys, you must use std::stable_sort(first, last, comp) 如果您只想比较count并保持相等顺序的原始顺序,则必须使用std::stable_sort(first, last, comp)

Sorts the elements in the range [first, last) in ascending order. 按升序对[first,last)范围内的元素进行排序。 The order of equal elements is guaranteed to be preserved. 相等元素的顺序保证得到保留。

with an appropriate comparison operator 与适当的比较运算符

std::stable_sort(vect.begin(), vect.end(),
     [](const std::pair<int, T> &x, const std::pair<int, T> &y) {
        return x.first < y.first;
     }
);

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM