std::sort 对列表如何工作? [英] How does std::sort work for list of pairs?
本文介绍了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::sort
按 second
排序?
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;
});
这篇关于std::sort 对列表如何工作?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!
查看全文