-3

If I have the following vector:

vector< pair < pair< char,int >,pair< int,int > > >

How can I sort in descending order using <algorithm> library according to the integer part in the first pair? (I want to use sort(vector.begin() , vector.end() )

IVlad
  • 43,099
  • 13
  • 111
  • 179

3 Answers3

4
using MyVector = vector< pair < pair< char,int >,pair< int,int > > >;
MyVector v;
std::sort(v.begin(), v.end(),
    [](const MyVector::value_type& a, const MyVector::value_type& b) {
      return a.first.second > b.first.second;
    }
);
Igor Tandetnik
  • 50,461
  • 4
  • 56
  • 85
1
std::sort( v.begin(), v.end(), 
    []( const auto &p1, const auto &p2 ) { return p1.first.second > p2.first.second; } );  

If your compiler does not support auto in lambda expressions then you have to specify the type of the vector elements explicitly for example using a typedef.

Vlad from Moscow
  • 301,070
  • 26
  • 186
  • 335
1

I think you can use this link as a reference:

sort(mMyClassVector.begin(), mMyClassVector.end(), 
    [](const MyClass & a, const MyClass & b) -> bool
{ 
    return a.mProperty > b.mProperty; 
});

Use lambda and define what should be '>' when you get two objects from your vector.

Alex Lop.
  • 6,810
  • 1
  • 26
  • 45