1

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

  • If that's the set you created it's already "sorted" on the tie of first,second. If you want a *different* ordering from inception, provide a custom comparison type for the comparator argument of [`std::set`](https://en.cppreference.com/w/cpp/container/set) (see the second template argument). Optionally, you *can* provide a comparator instance override at instantiation (see options #1 and #2 of [`std::set::set`](https://en.cppreference.com/w/cpp/container/set/set). – WhozCraig Dec 29 '19 at 13:46
  • 1
    I'm tempted to close as a dupe of https://stackoverflow.com/questions/2620862/using-custom-stdset-comparator – HolyBlackCat Dec 29 '19 at 13:49

1 Answers1

1

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;
Paul Evans
  • 27,315
  • 3
  • 37
  • 54
  • [Effective STL](https://www.amazon.co.uk/Effective-STL-Specific-Professional-Computing/dp/0201749629) by Scott Meyers. A bit out of date c++11 wise but bang on the money for understanding how the STL library works (which is totally current). – Paul Evans Dec 29 '19 at 17:39