std::sort 对列表如何工作?

std::sort 对列表如何工作?

问题描述:

为什么这个:

#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;
    }
}

按预期工作?输出为:

1
2
2
5
6

std::sort 如何获得如何对我的 int-string 对进行排序?如何让我的某类人以 first 的形式这样做?有没有办法使用 std::sortsecond 排序?

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?

自从 operator 是为 std::pair 定义的,它基于 std::pair::first 然后是 std::pair::second (字典序),所以你的代码是作为标准工作的.要根据 std::pair 的第二部分对其进行排序,您可以尝试:

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;
});