Sort a vector of pairs by first element then by second element of the pair in C++? [duplicate]

StackOverflow https://stackoverflow.com/questions/18029110

  •  23-06-2022
  •  | 
  •  

문제

If I have a vector<pair<int,int> > datatype, what is the accepted way to sort it by the first element of the pair and then by second if the firsts are equal? For instance maybe (1,10), (3,3), (7,13), (7,16), (8,1), (8,2), (15,2) etc.

도움이 되었습니까?

해결책

pairs by default compare by first element, then second. So, if you don't care about preserving the order when the first elements compare equal, then you can just use std::sort:

std::sort(v.begin(), v.end());

다른 팁

std::pairs comparison operators compare pairs lexicographically, it first compares the first elements, then the second elements if the first elements are equal.

Here is an example of using std::vector<std::pair<int, int>> and std::sort.

Using std::sort that way uses std::pair's operator <, which, as said above, compares the pairs lexicographically.

UPDATE: Here is an example using std::stable_sort and a custom comparison function that compares only the first element.

By using std::stable_sort, you are guaranteed that the relative order of equal elements are preserved. That is, even if the first elements of the std::pairs are equal, the original relative order is still retained.

라이센스 : CC-BY-SA ~와 함께 속성
제휴하지 않습니다 StackOverflow
scroll top