如何对向量< 对< int 、对<int 、<对字符串、对<int 、int > > > > >进行排序?
How to sort vector< pair< int , pair<int , pair<string , pair<int , int > > > > >?
我正在学习使用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);
相关文章:
- 请解释这句话(cout<<1+int((a<b)^((b-a)&1) )<<endl
- 呼叫运营商<<临时
- 如何防止clang格式在流运算符调用之间添加换行符<<
- <<操作员在下面的行中工作
- EASTL矢量<向量<int>>连续的
- C - 创建矢量&lt; vector&lt; double&gt;&gt;矩阵具有分配而不是inizializ
- 为什么将此对向量&lt; map&lt; int,int&gt;&gt;中的地图进行更新.失败
- C :对矢量进行排序&lt; struct&gt;(结构有2个整数)基于结构的整数之一
- 明确的专业化“ CheckIntmap&lt;&gt;”实例化
- 什么是模板&lt;&gt;inline bla bla
- 编辑C Qlist&lt; object*&gt; gt;QML代码和一些QML警告中的模型
- eigen :: llt&lt;eigen :: matrixxd&gt;具有不完整的类型
- 错误,包括&lt; ctype&gt;在原子上使用C 11
- std::vector<;uint8_t>;当C++11/14启用时,手动复制而不是调用memcpy
- 如何加入向量&lt; int&gt;到C 中的单个INT
- 是std :: set&lt; std :: future&gt;不可能存在
- 是numeric_limits&lt; int&gt; :: is_modulo从逻辑上矛盾
- opencv 2.4.7在iOS错误背景_segm.hpp #include&lt; list&gt;未找到
- 在修改列表后,std :: list&lt; t&gt; :: end()的值是否会更改
- ///<评论></评论>在Visual Studio中