簡體   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 > > > > >?

我正在學習通過將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::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);

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM