简体   繁体   English

如何对vector &lt;pair &lt;int,pair进行排序 <int , pair<string , pair<int , int > &gt;&gt;&gt;&gt;?

[英]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. 我正在学习通过将STL的排序函数用于一些复杂的成对向量来使用它。

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. 我首先需要基于该对中的第一个整数对元素进行排序,如果事实证明有2个元素具有相同的值,那么我需要根据内部对中存在的整数对它们进行排序。

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? 首先,我需要根据I对它们进行排序,然后根据G对它们进行排序。仅使用比较器就可以有效地做到这一点吗?

Call std::sort(RandomIt first, RandomIt last) passing a suitable comparison function as comp . 调用std::sort(RandomIt first, RandomIt last)并将合适的比较函数作为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. 对于您的特定情况, std::pair的默认比较将起作用。

http://en.cppreference.com/w/cpp/utility/pair/operator_cmp 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. 如果lhs.first <rhs.first,则返回true。 Otherwise, if rhs.first < lhs.first, returns false. 否则,如果rhs.first <lhs.first,则返回false。 Otherwise, if lhs.second < rhs.second, returns true. 否则,如果lhs.second <rhs.second,则返回true。 Otherwise, returns false. 否则,返回false。

In C++11, if you need to choose the sorting criterion at runtime, you can use a lambda for comparison. 在C ++ 11中,如果需要在运行时选择排序条件,则可以使用lambda进行比较。 It should take const references to the type, and return bool. 它应该使用const引用该类型,并返回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);

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

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