2011-01-22 93 views
1

地圖我有類似的圖:排序由大小

map<int, map<int, map<int, int> > > myMap; 

order-num | id | order-num-of-relation | relation-id 
----------------------------------------------------- 
    0  | 1 | 0      | 2 
----------------------------------------------------- 
    1  | 2 | 0      | 1 
----------------------------------------------------- 
      | | 1      | 3 
----------------------------------------------------- 
    2  | 3 | 0      | 2 
----------------------------------------------------- 

1(1),2(2),3(1)

,我需要進行排序(改變 「訂單NUM」 )按照最後一張地圖(order-num-of-relation | relation-id)的大小繪製該地圖。

我只需要做到這一點:

order-num | id | order-num-of-relation | relation-id 
----------------------------------------------------- 
    0  | 1 | 0      | 2 
----------------------------------------------------- 
    1  | 3 | 0      | 2 
----------------------------------------------------- 
    2  | 2 | 0      | 1 
----------------------------------------------------- 
      | | 1      | 3 
----------------------------------------------------- 

1(1),3(1),2(2)

我可以使用 「排序」 功能,並通過這裏擁有排序功能(在哪裏我可以檢查大小和Returing真/假),還是我必須編寫明確的排序算法?

+0

地圖是按順序排列的,並且在聲明它時以固定順序作爲模板的參數。您不能根據不同的順序重新排序地圖,因爲您需要將數據移動到不同的容器中,然後在那裏處理它。另請注意,地圖元素中的鍵不能在插入後更改。 – 2011-01-22 21:08:33

回答

2

您不能/不能排序地圖。它們根據模板參數的可選第三個參數自動按鍵排序,這是一個函數對象類,用於比較兩個元素以確定哪個應該先到達。 (它應該返回true,如果第一個要來的前一秒,否則爲false)

所以,你可以使用這樣的事情:

struct myCompare 
{ 
    bool operator() const (const map<int,int> & lhs, const map<int,int> & rhs) 
    { 
     return lhs.size() < rhs.size(); 
    } 
}; 

但由於map<int,int>是你的價值,而不是你的鑰匙,這韓元你確切地爲你工作。

+0

爲什麼這不適合我?只需要一些begin() - > second或sth。像那樣,還是不? – 2011-01-22 20:48:36

2

您正在尋找的東西已經在Boost MultiIndex中完成。 Boost提供了一個很好的tutorial,您可以使用它來解決您要求的數據收集以及他們對examples的選擇。

當然,使用這個集合對象可能會改變你存儲信息的方式。你會把它放在一個結構中。但是,如果你想按照規範的方式將你的信息像一個具有唯一順序的數據庫一樣對待,那麼這就是我知道這是乾淨的唯一途徑。

另一種選擇是在將項目放置在std :: map中時創建自己的訂購操作員。因此:

struct Orders{ 
    int order_num; 
    int id; 
    int order_num_relation; 
    int relation_id; 

    bool operator<(const Orders& _rhs){ 
     if(order_num < _rhs.order_num) return true; 
     if(order_num == _rhs.order_num){ 
      if(id < _rhs.id) return true; 
      if(id == _rhs.id){ 
       //and so on, and so on 

老實說,這種方式是一種痛苦,並引起一個非常容易被忽視的邏輯錯誤。使用Boost,大部分「棘手」的東西都會爲您照顧。