2015-08-15 109 views
0

我有一個類看起來像這樣C++:二維靜態地圖的初始化

class MapClass { 
public: 
    static map<string, map<string, double>>  spreadMap; 
}; 

那麼既然是可以初始化一個標準的地圖是這樣的:

map<string,int> AnotherClass::standardMap = { 
    {"A",0}, 
    {"B",1}, 
    {"C",2} 
}; 

我試着做同樣的2D地圖:

map<string, map<string, double>> MapClass::spreadMap = { 
    {"A", {"B", 0}}, 
    {"C", {"D", 1}}, 
    {"E", {"F", 2}} 
}; 

但顯然它不工作。錯誤信息是:

error: could not convert '{{"A", {"B", 0}}, {"C", {"D", 1}}, {"E", {"F", 2}}}' from '<brace-enclosed initializer list>' to 'std::map<std::basic_string<char>, std::map<std::basic_string<char>, double> >' 

有沒有人知道如何解決這個問題,如果可能的話沒有某種初始化函數。

非常感謝!

+0

如何?{{「A」,{{「B」,0}}}}? – Quentin

回答

1

事實上,你已經在你的文章解決方案。

標準的簡單地圖initilisation,你向我們展示是

map<string,int> AnotherClass::standardMap = 
{ // opening brace for the map 
    {"A",0}, // first value for the map 
    {"B",1}, // second value 
    {"C",2} // ... 
}; // closing brace for the map 

但在複雜的地圖,你寫的(我加了註釋):

map<string, map<string, double>> MapClass::spreadMap = 
{ // opening brace for the map of map 
    {    // opening of a brace for a first element 
     "A",   // first key 
     {"B", 0} // first value which should be a map initializer 
    },    // closing of the brace for the first element 
    {"C", {"D", 1}}, // second element with second map 
    {"E", {"F", 2}} // ... 
}; // closing brace for the map of map 

正如你所看到的,當你比較內部映射初始化與您以前的工作代碼,有一個不一致:內部映射的初始化程序列表的周圍大括號。如果內部映射應該用幾個元素初始化,你會如何編寫它?

的解決辦法是添加缺少的括號:

map<string, map<string, double>> MapClass::spreadMap = 
{ // opening brace for the map of map 
    {    // opening of a brace for a first element 
     "A",   // first key 
     {   // <<<<= opening brace for the first value wich is a map 
      {"B", 0} // pair of key, value for the inner map 
     }   // <<<<= closing brace for the inner map 
    },    // closing of the brace for the first element 
    {"C", {{"D", 1}}}, // second element with second map 
    {"E", {{"F", 2},{"G",3}}} // (the inner map could have itself several values... 
}; // closing brace for the map of map 

這裏一個live demo。 (順便說一句,你不需要=這裏。