2013-11-22 61 views
1

我希望能夠排序以下矢量 - 矢量<對<字符串,對< int,int>>>基於對的第一個元素< int,int>,如果它們相等,則按照到他們的第二個元素,我怎麼用C++來使用STL的構造呢?如何對一個向量進行排序<pair <string,pair <int , int> >>?

這類必須完成對這個

線的東西讓說E1和E2是2元

如果E1.second.first == E2.second.first則比較必須由關於第二個要素。

回答

2

如果您不能使用C++ 11層的功能,你仍然可以做這樣的事情:

typedef std::pair<std::string, std::pair<int, int>> AnkitSablok; 

struct my_compare { 
    bool operator()(const AnkitSablok &lhs, const AnkitSablok &rhs) const { 
     return lhs.second < rhs.second; 
    } 
}; 

int main() 
{ 
    std::vector<AnkitSablok> vec; 

    std::sort(vec.begin(), vec.end(), my_compare()); 
} 
+0

它的工作原理:D,感謝blastfurnace做出如此大的回覆:D,感謝你,一般來說,你能向我解釋如何完成這樣的工作嗎?一些理論將是有用的:) – AnkitSablok

+1

[在C + + 03本地類不能用作模板參數](http://stackoverflow.com/a/5751990/1762344)。 –

+0

@EvgenyPanasyuk:謝謝,我已經使用嚴格的C++ 03編譯器已經有一段時間了。 – Blastfurnace

0
sort(x.begin, x.end, [](const X & a, const X & b){return a.second.first < b.second.first ; }) ; 

其中x是您的容器,X是元素的類型。

+0

你能解釋一下你剛剛做了什麼嗎? – AnkitSablok

+0

另外,你能解決錯別字嗎? c: –

+0

這是用作比較函數的標準庫+ lambda函數的排序函數。 – zoska

2

[...]基於對的第1個要素上< INT,INT>如果這些是相等的,那麼根據它們的第二元件對它們進行排序[...]

std::pair已經逐一比較C++ 03 20.2.2/6:

template <class T1, class T2> 
bool operator<(const pair<T1, T2>& x, const pair<T1, T2>& y); 

Returns: x.first < y.first || (!(y.first < x.first) && x.second < y.second) 

因此,正如WhozCraig指出的那樣,您應該比較外部對的.second

這是一個lambda表達式,我沒有C++ 11與我,有沒有其他方式可能?

使用仿函數:

struct LessSecond 
{ 
    template<typename T, typename U> 
    bool operator()(const std::pair<T,U> &x, const std::pair<T,U> &y) const 
    { 
     return x.second < y.second; 
    } 
}; 
// ... 
sort(x.begin(), x.end(), LessSecond()); 

也許更寬泛的版本(取決於您的需要):

struct LessSecondGeneric 
{ 
    template<typename Pair> 
    bool operator()(const Pair &x, const Pair &y) const 
    { 
     return x.second < y.second; 
    } 
}; 

LIVE DEMO

#include <algorithm> 
#include <iostream> 
#include <iterator> 
#include <utility> 
#include <vector> 

struct LessSecond 
{ 
    template<typename T, typename U> 
    bool operator()(const std::pair<T,U> &x, const std::pair<T,U> &y) const 
    { 
     return x.second < y.second; 
    } 
}; 

int main() 
{ 
    using namespace std; 

    vector<pair<string , pair<int, int>>> x 
    { 
     {"1", {2, 1}}, {"2", {1, 1}}, {"3", {1, 2}} 
    }; 
    sort(x.begin(), x.end(), LessSecond()); 
    for(const auto &p : x) 
     cout << p.first << " (" << p.second.first << ", " << p.second.second << ")" << endl; 
} 

輸出是:

2 (1, 1) 
3 (1, 2) 
1 (2, 1) 
+0

好的。那會讓OP陷入昏迷狀態,但我更喜歡它,特別是因爲它是通用的。我正在傾銷我的答案。 +1 – WhozCraig

相關問題