-3

How do i sort pair like this for example :

Input :

1 99

2 100

1 100

3 400

2 101

output :

1 100

1 99

2 101

2 100

3 400

nff21
  • 45
  • 7

1 Answers1

2

Create a comparator and use the std::sort function.

struct Comp {
  bool operator()(const std::pair<int, int> &a, const std::pair<int, int> &b) {
    if (a.first != b.first) {
      return a.first < b.first;
    }
    return a.second > b.second;
  }

};

Then create an instance of the struct and pass it into std::sort.

Comp comp_functor;
std::sort(myVec.begin(), myVec.end(), comp_functor);

To do this you'd need to #include <algorithm>. Also note that std::sort does not guarantee stability so if you want stability use std::stable_sort.

NickLamp
  • 862
  • 5
  • 10
  • You shouldn't be enabling users that ask bad questions (i.e., that are off-topic), see [here](http://stackoverflow.com/help/on-topic), by answering them. – James Adkison Mar 03 '16 at 15:41
  • As written, if `b.first` is greater than `a.first` it starts comparing on `second` ... – James Adkison Mar 03 '16 at 15:43
  • I saw the comment chain above but decided to post anyway because I thought the user might benefit from learning about what a comparator is (I'm assuming he hasn't seen them before, otherwise this exercise would have been trivial for him). Although the way he worded his question wasn't good I still think he deserves a well thought out answer. – NickLamp Mar 03 '16 at 15:44