std :: sort如何用于列表对?

Duc*_*een 8 c++ sorting algorithm stl std

为什么这样:

#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;
    }
}
Run Code Online (Sandbox Code Playgroud)

按计划工作?输出是:

1
2
2
5
6
Run Code Online (Sandbox Code Playgroud)

如何std::sort对我的int-string对进行排序?如何让它成为我的一些类的一对first?有没有办法按second使用排序std::sort

mas*_*oud 6

既然operator<是定义的std::pair,它是基于std::pair::first然后std::pair::second(词典编纂),所以你的代码作为标准.要根据std::pair您的第二部分对其进行排序,您可以尝试这样做:

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


Nik*_* B. 5

由组件的各自排序引起的产品类型有一个"明显的"排序,这是词典顺序:

(a, b) < (c, d)  <=>  a < c || (a == c && b < d)
Run Code Online (Sandbox Code Playgroud)

这是所使用的排序operator<std::pair.在您的示例中,由于所有第一个组件都是不同的,因此排序恰好等于第一个组件的排序.如果在第一个组件中有多个相同值的出现,其中第二个组件用于断开连接,则会更有趣.

如何让它成为第一对我某类的一类?

您只需要operator<为您的类型定义.但请记住,如有必要,考虑第二个组件,您可能不需要这种开销.

有没有办法按second使用排序std::sort

是的,只需使用自定义比较器仿函数.如果您不想使用默认operator<排序,则可以随时执行此操作.