[英]sort a pair vector in c++
#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;
}
上面代碼的輸出是---
1 3
4 2
5 4
我們可以從輸出中看到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;});
std::sort()
函數接受比較函數對象作為參數:
template<class RandomIt, class Compare> void sort(
RandomIt first, RandomIt last, Compare comp);
second
成員pair
工作比較函數是:
bool cmp(const std::pair<int,int>& a, const std::pair<int,int>& b) {
return a.second < b.second;
}
默認情況下,它會根據您的程序正在進行的第一個元素排序。 但是你可以傳遞第三個參數來排序為你定義的比較器來做你想做的事......
您可以使用自己的比較器對右側元素進行排序: -
struct sort_second {
bool operator()(const std::pair<int,int> &left, const std::pair<int,int> &right) {
return left.second < right.second;
}
};
std::sort(v.begin(), v.end(), sort_second());
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.