Search code examples
c++sortingsetstd-pairstdset

Is there any way to sort set of pair of int and pair by greater int and smaller pair in c++?


I have a set<int, pair<int, int> > ms that I want to sort it by greater int and smaller pair<int, int>. For example, if these are the data in my set:

<10, pair<100, 120> >
<20, pair<45, 60> > 
<20, pair<50, 10> >

I want it to be this after sorting operation:

<20, pair<45, 60> >
<20, pair<50, 10>
<10, pair<100, 120> >

I know I can insert in set in descending order by std::greater but I don't know how to combine descending and ascending!


Solution

  • Pass a custom compare operator to std::sort.

    #include <iostream>
    #include <vector>
    #include <utility>
    #include <algorithm>
    
    int main() {
      std::vector<std::pair<int, std::pair<int, int>>> v = {
        std::make_pair(10, std::make_pair(100, 120)),
        std::make_pair(20, std::make_pair(45, 60)), 
        std::make_pair(20, std::make_pair(50, 10)),
      };
    
      std::sort(v.begin(), v.end(), [](const auto &lhs, const auto &rhs) -> bool {
          if (std::get<0>(lhs) > std::get<0>(rhs))
            return true;
          else if (std::get<0>(lhs) < std::get<0>(rhs))
            return false;
          else
            return std::get<1>(lhs) < std::get<1>(rhs);
      });
    
      for (const auto &e : v) {
        std::cout << e.first << " " << e.second.first << " " << e.second.second;
        std::cout << "\n";
      }
    }
    

    https://repl.it/repls/ComfortableAfraidKernelmode