2013-11-23 204 views
0

我正在学习使用STL的排序功能,将它用于某些复杂的对子对。如何对矢量<pair <int,pair <int,pair <string,pair <int , int >>>>>进行排序

我有以下矢量:

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

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

如果我代表上述类型:

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

首先我需要根据我对它们进行排序,然后根据G.可以这样高效地完成,只用比较?

+0

你的排序代码是什么样的?你有任何代码可以分享吗? – Soren

+1

我厌倦了在其他答案中重复这一点。 [std :: pair implements](http://en.cppreference.com/w/cpp/utility/pair/operator_cmp)字典对比。所有你需要做的就是调用'std :: sort',并且它可以开箱即用。注意标准库的力量。 – StoryTeller

回答

1

呼叫std::sort(RandomIt first, RandomIt last)通过合适的比较函数compdefault comparison function将按照您希望他们订购的方式比较元素。

+0

我认为默认的会做。 [std :: pair define](http://en.cppreference.com/w/cpp/utility/pair/operator_cmp)几个模板化词典比较运算符。 – StoryTeller

+0

问题:“我想使用'std :: sort',但是如何编写该比较器?”答案:“用合适的比较器调用'std :: sort'”。 –

+0

问题是如何排序矢量,而不是如何编写一个comperator。 “这可以通过使用比较器有效地完成吗?”嗯,是。 – Oswald

0

对于您的特定情况,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引用类型,并返回布尔值。

这是它的样子。

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

我需要一个结构比较器来做到这一点没有C++ 11 – AnkitSablok

+0

你到目前为止尝试过什么。编写自定义比较运算符是SO上非常常见的问题。 – NicholasM

相关问题