在C ++中按第一个元素和第二个元素对第一个元素的矢量进行排序?

时间:2013-08-03 04:01:53

标签: c++ sorting vector std-pair

如果我有一个vector<pair<int,int> >数据类型,那么通过该对的第一个元素对它进行排序的可接受方式是什么,然后如果第一个相等则按秒进行排序?例如,可能是(1,10),(3,3),(7,13),(7,16),(8,1),(8,2),(15,2)等。

2 个答案:

答案 0 :(得分:8)

默认情况下,

pair比较第一个元素,然后是第二个元素。因此,如果您在第一个元素比较相等时不关心保留顺序,那么您可以使用std::sort

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

答案 1 :(得分:1)

std::pairs comparison operators按字典顺序比较对,它首先比较第一个元素,然后第二个元素,如果第一个元素相等。

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

std::sort方式使用std::pair的{​​{1}},如上所述,按字典顺序对这些对进行比较。

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

通过使用std::stable_sort,可以保证保留相等元素的相对顺序。也就是说,即使operator <的第一个元素相等,原始相对顺序仍然保留。

相关问题