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

柔情痞子 提交于 2019-11-28 13:14:58

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.

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!