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
Sorts the elements in the range [first, last) in ascending order. The order of equal elements is not guaranteed to be preserved.
1) Elements are compared using operator<.
and from std::pair::operator<
3) If lhs.first < rhs.first, returns true. Otherwise, if rhs.first < lhs.first, returns false. Otherwise, if lhs.second < rhs.second, returns true. Otherwise, returns false.
So effectively, sort compares count[i]
, and if two of them are equal, it compares 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)
Sorts the elements in the range [first, last) in ascending order. 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;
}
);
The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.