如何对向量< 对< int 、对<int 、<对字符串、对<int 、int > > > > >进行排序?

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

本文关键字:lt gt int 排序 向量 字符串      更新时间:2023-10-16

我正在学习使用STL的排序函数,将其用于一些复杂的对向量。

我有以下矢量:

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

我需要首先根据对中的第一个整数对元素进行排序,如果结果是有两个元素的值相同,那么我需要根据内部对中的整数对它们进行排序。

如果我将上述类型表示为:

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

首先,我需要根据I,然后根据G对它们进行排序。这可以有效地完成吗,只使用比较器?

调用std::sort(RandomIt first, RandomIt last),将合适的比较函数作为comp传递。默认的比较函数将按照您希望的排列方式对元素进行比较。

对于您的特定情况,std::pair中的默认比较将起作用。

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 );

通过一个递归步骤应用这个规则,可以看到情况是这样的:

如果lhs.first<rhs.first,返回true。否则,如果rhs.first<lhs.first,返回false。否则,如果lhs.second<rhs.second,返回true。否则,返回false。

在C++11中,如果需要在运行时选择排序标准,可以使用lambda进行比较。它应该接受对类型的const引用,并返回bool。

这是它的样子。

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);