user12007154
user12007154

Reputation:

How to sort set of pairs in STL c++ according to second element of pair?

Suppose i have created

set<pair<int,int>> s

I want it to get automatically sorted on the basis of second element of pair .How to do this ? I searched on web but did not found any solution. can we have some external function for this ? Thanks

Upvotes: 1

Views: 1772

Answers (1)

Paul Evans
Paul Evans

Reputation: 27577

Use std::set with a custom compare functor:

using pair_type = std::pair<int, int>;
struct PairCmp
{
    bool operator()(const pair_type& lhs, const pair_type& rhs) const
    { 
        return lhs.second < rhs.second; 
    }
};
std::set<pair_type, PairCmp> s;

Upvotes: 1

Related Questions