How does std::sort work for list of pairs?

僤鯓⒐⒋嵵緔 提交于 2021-01-22 03:53:57

问题


Why does this:

#include <iostream>
#include <string>
#include <vector>                                                             
#include <algorithm>

using namespace std;

vector<pair<int, string>> list;

int main() {
    int one = 1, two = 2, three =3, five =5, six = 6;
    string bla = "bla";

    list.push_back( pair<int, string>(two, bla));
    list.push_back( pair<int, string>(one, bla));
    list.push_back( pair<int, string>(two, bla));
    list.push_back( pair<int, string>(six, bla));
    list.push_back( pair<int, string>(five, bla));

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

    for(auto item : list) {
        cout << item.first << endl;
    }
}

work as intended? output is:

1
2
2
5
6

How std::sort gets how to sort my int-string pairs? How to make it do so for some class of mine as pair first? Is there a way to sort by second using std::sort?


回答1:


Since operator< is defined for std::pair and it is based on std::pair::first and then std::pair::second (lexicographical), so your code is working as the standard. To sort it based on the second part of the std::pair you can try this:

std::sort(list.begin(), list.end(), [](const std::pair<int, string> &x,
                                       const std::pair<int, string> &y)
{
    return x.second < y.second;
});



回答2:


There is one "obvious" ordering of product types induced by the respective orderings of the components, and that is lexicographical order:

(a, b) < (c, d)  <=>  a < c || (a == c && b < d)

This is the ordering used by operator< of std::pair. In your example, since all the first components are distinct, the ordering happens to be equal to the ordering of the first component. It gets more interesting if you have multiple occurences of the same value in the first component, in which the second component is used to break ties.

How to make it do so for some class of mine as pair first?

You just have to define operator< for your type. But keep in mind that the second component will be considered if necessary and you might not want that overhead.

Is there a way to sort by second using std::sort?

Yes, just use a custom comparator functor. You can always do that if you don't want to use the default operator< for sorting.



来源:https://stackoverflow.com/questions/23816797/how-does-stdsort-work-for-list-of-pairs

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