0

After searching on google for some time I was not able to find a answer specifically answering this question. How to reverse sort a c++ STL pair with some custom type in it

pair <long long, pair< int, int > > p[MAX];
Amit Tripathi
  • 7,003
  • 6
  • 32
  • 58
  • @frerich-raabe No. Thats vector of pair with standard c++ data types and in my question its array of pairs with(can be customized) custom types in it. – Amit Tripathi Jul 29 '15 at 19:20
  • If you compare the answers, you'll see that the types of the two fields of the `std::pair` values don't matter. The solution is always some sort of comparison function which checks one (or both) of the fields. I don't think it's helpful to create new questions for any plausible configuration of std::pair. – Frerich Raabe Jul 29 '15 at 20:01

2 Answers2

4
#include<bits/stdc++.h>
using namespace std;

const int MAX = 1e5 + 5;
typedif pair <long long, pair< int, int > > pll;
pll p[MAX];

//custom sort function can be customized
bool SortByWeight(pll x, pll y){ 
    return x.first > y.first;
}

int main(){
    //enter size
    cin>>szie;
    //Ex: p = [(10101, (2,3)), (129334, (4, 7))....]
    sort(p, p+size, SortByWeight)
}

Custom function can be customized for custom type. For ex for class we can use use class_obj.variable_name etc

Amit Tripathi
  • 7,003
  • 6
  • 32
  • 58
0

std::pair provides a member-wise operator < on its own (as well as operator >), so all you need to do is ask std::sort to use operator >:

std::sort(p, p + MAX, std::greater<pair <long long, pair< int, int > >>());

More documentation here: std::pair, std::sort, std::greater.

UnknownGosu
  • 854
  • 6
  • 9