2014-07-24 76 views
-1

我有一個帶有兩個成員的結構int和一個字符串。將結構映射爲鍵和結構的向量作爲其值聲明

struct A 
{ 
int a; 
string b; 
} 

vector<A> pl; 
pl = getPL(); //getPL returns a vector<A> 
for (auto: pl) 
{ 
vector<A>tr; 
tr = getTR() //getTR returns vector<A> 
for(auto: tr) 
{ 
    //store tr somewhere.. 
} 

} 

我想創建一個map<A, vector<A>>讓每個PL對象可以容納一個載體。怎麼做?在C++中有沒有其他方式或數據結構可以實現我正在嘗試做的事情。 謝謝,

+0

'for(auto:pl)' - 編譯?另外,我不確定你的問題是什麼。爲什麼'map >'不適合你? –

+0

我知道不會編譯。它應該是(自動i:pl)。我實際上正在尋找如何將結果存儲在地圖中。地圖>類似的東西。 – user2391188

+0

要使用'A'作爲地圖中的關鍵字,您需要爲其定義'operator <'或使用自定義'key_compare'函數提供地圖。 – dlf

回答

1

std::map s保持他們的數據按鍵排序。但要做到這一點,他們需要一些方法來比較兩個關鍵對象,並確定哪一個應該優先。默認情況下,這種比較是使用<運算符完成的,但該運算未定義爲A,它可能(可能)解釋了您(可能)看到的編譯錯誤。

所以;要使用A作爲std::map中的關鍵字,您需要爲其定義operator <或提供具有自定義key_compare仿函數的映射。下面的代碼演示了兩種方法:

#include <map> 
#include <string> 
#include <vector> 

struct A 
{ 
    int a; 
    std::string b; 
}; 

bool operator <(const A& l, const A& r) 
{ 
    if(l.a != r.a) 
     return l.a < r.a; 
    return l.b < r.b; 
} 

struct B 
{ 
    int a; 
    std::string b; 
}; 

struct CompareBs 
{ 
    bool operator()(const B& l, const B& r) const 
    { 
     if(l.a != r.a) 
      return l.a < r.a; 
     return l.b < r.b; 
    } 
}; 

int main() 
{ 
    std::map<A, std::vector<A>> aMap; 
    std::map<B, std::vector<B>, CompareBs> bMap; 
    return 0; 
} 
+0

非常感謝@dlf可行! – user2391188

+0

@ user2391188好的;很高興它有幫助。 – dlf

+0

你能解釋一下現在填寫/填寫這張地圖嗎?謝謝。 – user2391188