gsdf
gsdf

Reputation: 285

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;
}

The output to the above code is---

1 3 
4 2
5 4

We can see from the output that sort function has sorted v[i].first but what if we only want to sort v[i].second or if we want to sort both of them,how to then accomplish the task?

Upvotes: 4

Views: 3070

Answers (3)

Anton Savin
Anton Savin

Reputation: 41301

Specify your custom comparer. In C++14 it can be done very concisely:

sort(v.begin(), v.end(), [](const auto& x, const auto& y){return x.second < y.second;});

Upvotes: 6

ravi
ravi

Reputation: 10733

By default it would sort on the basis of first element much as your program is doing. However you could pass third argument to sort as your-defined comparator to do what-ever you want to do...

You can have your own comparator for sorting on right element:-

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());

Upvotes: 2

slaphappy
slaphappy

Reputation: 6999

The std::sort() function accepts a comparison function object as a parameter:

template<class RandomIt, class Compare> void sort(
    RandomIt first, RandomIt last, Compare comp);

A working comparison function for the second member of pair would be:

bool cmp(const std::pair<int,int>& a, const std::pair<int,int>& b) {
    return a.second < b.second;
}

Upvotes: 2

Related Questions