简体   繁体   中英

How to sort vector< pair< int , pair<int , pair<string , pair<int , int > > > > >?

I am learning to use STL's sort function by putting it to use to some complex vector of pairs.

I have the following vector:

vector< pair< int , pair< int , pair< string , pair< int , int > > > > >

I need to first sort the elements based on the first integer in the pair, and if it turns out that there are 2 elements with the identical values, then I need to sort them on the basis of the integer present in the inner pair.

if I represent the above type as:

vector< pair< I , pair< G , pair< S , pair< T , T > > > > >

first I need to sort them according to I and then according to G. Can this be done efficiently, just using comparators?

Call std::sort(RandomIt first, RandomIt last) passing a suitable comparison function as comp . The default comparison function will compare elements the way that you want them ordered.

For your particular case, the default comparison within std::pair will work.

http://en.cppreference.com/w/cpp/utility/pair/operator_cmp

template< class T1, class T2 >
bool operator<( const pair<T1,T2>& lhs, const pair<T1,T2>& rhs );

Apply this rule with one recursion step to see that this is the case:

If lhs.first < rhs.first, returns true. Otherwise, if rhs.first < lhs.first, returns false. Otherwise, if lhs.second < rhs.second, returns true. Otherwise, returns false.

In C++11, if you need to choose the sorting criterion at runtime, you can use a lambda for comparison. It should take const references to the type, and return bool.

Here is what it would look like.

typedef pair< int , pair< int , pair< string , pair< int , int > > > > MyComplexType;
std::vector<MyComplexType> v;
// fill v

// sort
auto complexLessThan = [](const MyComplexType& left, const MyComplexType& right)  -> bool
{
    // your sorting criterion here           
}

std::sort(v.begin(), v.end(), complexLessThan);

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM