Sort paired 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;
}
Conclusion to the specified code ---
1 3
4 2
5 4
The output shows that the sort function sorted v [i] .first, but what if we only want to sort v [i]. seconds or if we want to sort both of them, how do we accomplish the task?
source to share
The function std::sort()
takes a comparison function object as a parameter:
template<class RandomIt, class Compare> void sort(
RandomIt first, RandomIt last, Compare comp);
Working comparison function for member second
pair
:
bool cmp(const std::pair<int,int>& a, const std::pair<int,int>& b) {
return a.second < b.second;
}
source to share
By default, it will sort based on the first element like your program does. However, you could pass a third argument to sort as your specific comparator to do what you want to do ...
You can have your own right-sorted comparator: -
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());
source to share