【问题标题】:How to sort vector< pair< int , pair<int , pair<string , pair<int , int > > > > >?如何对向量< pair< int , pair<int , pair<string , pair<int , int > > > > > 进行排序?
【发布时间】:2013-11-23 22:53:10
【问题描述】:

我正在学习使用 STL 的排序功能,方法是将它用于一些复杂的对向量。

我有以下向量:

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

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

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

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

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

【问题讨论】:

  • 您的排序代码是什么样的?你有代码要分享吗?
  • 我厌倦了在其他答案中重复这一点。 std::pair implements 字典比较。您需要做的就是致电std::sort,它会开箱即用。看看标准库的力量吧。

标签: c++ sorting vector stl


【解决方案1】:

调用std::sort(RandomIt first, RandomIt last) 传递一个合适的比较函数作为compdefault comparison function 将按照您希望它们排序的方式比较元素。

【讨论】:

  • 我认为默认的就可以了。 std::pair defines 几个模板化的字典比较运算符。
  • 问题:“我想使用std::sort,但是如何编写比较器?”答案:“使用合适的比较器致电std::sort”。
  • 问题是如何对向量进行排序,而不是如何编写比较器。 “仅使用比较器就可以有效地完成这项工作吗?”嗯,是的。
  • @Joker_vD,答案是标准库会在这里为我们的朋友生成一个合适的operator&lt;
  • @StoryTeller 确实如此。太好了,因为我见过导致“有趣”错误的非全部比较器。
【解决方案2】:

对于您的特定情况,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

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

【讨论】:

  • 我需要一个结构比较器来做这个我没有 C++11
  • 到目前为止你尝试了什么。编写自定义比较运算符是 SO 上非常常见的问题。
猜你喜欢
  • 1970-01-01
  • 1970-01-01
  • 2020-10-22
  • 2020-08-03
  • 2011-10-29
  • 1970-01-01
  • 1970-01-01
  • 2019-02-20
  • 2021-11-18
相关资源
最近更新 更多