0

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!

Parisa Mousavi
  • 52
  • 1
  • 11
  • 1
    Well, I picked the wrong duplicate and retracted my vote, so I can't vote again. Here is the correct link: [Sorting a vector of custom objects](https://stackoverflow.com/questions/1380463/sorting-a-vector-of-custom-objects). You basically have to write your own comparator for this. Maybe it would also help to write a class that holds three ints to add some semantic to those values, but that's unrelated. – Lukas-T Jul 01 '20 at 06:04
  • @churill Oh! I get your point. Thank you – Parisa Mousavi Jul 01 '20 at 06:07
  • What is `set>`? `set` has only one `Key` parameter. – Evg Jul 01 '20 at 06:07
  • @Evg No! It can have more than one – Parisa Mousavi Jul 01 '20 at 06:08
  • `template class set;`. With `set>`, `Key = int`, `Compare = pair`. This doesn't make sense. – Evg Jul 01 '20 at 06:09
  • @Evg I don't know what you are talking about – Parisa Mousavi Jul 01 '20 at 06:10
  • 1
    Try to compile `set>` and you'll see. – Evg Jul 01 '20 at 06:11
  • Let us [continue this discussion in chat](https://chat.stackoverflow.com/rooms/216995/discussion-between-parisa-mousavi-and-evg). – Parisa Mousavi Jul 01 '20 at 06:16

1 Answers1

1

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

Bill Lynch
  • 80,138
  • 16
  • 128
  • 173