gsd*_*sdf 4 c++ sorting vector std-pair
#include "bits/stdc++.h"
using namespace std;
int main()
{
int i,j;
vector< pair<int,int> > v;
v.push_back(make_pair(4,2));
v.push_back(make_pair(1,3));
v.push_back(make_pair(5,4));
sort(v.begin(), v.end());
for(i=0;i<v.size();i++)
cout<<v[i].first<<" "<<v[i].second<<endl;
}
Run Code Online (Sandbox Code Playgroud)
上述代码的输出是——
1 3
4 2
5 4
Run Code Online (Sandbox Code Playgroud)
从输出中我们可以看到sort函数已经对 v[i].first 进行了排序,但是如果我们只想对 v[i].second 进行排序或者如果我们想对它们两者进行排序,那么如何完成任务呢?
指定您的自定义比较器。在 C++14 中可以非常简洁地完成:
sort(v.begin(), v.end(), [](const auto& x, const auto& y){return x.second < y.second;});
Run Code Online (Sandbox Code Playgroud)