2013-03-17 230 views
1

基本上我有一個映射作爲一個類中的成員變量,我想用基本成員初始化部分中的鍵值對進行初始化。如何初始化C++中的基本成員初始化部分的std :: map?

Parser::Parser() 
    :operations() //the dictionary 
{ 

} 

我不太確定這樣做的語法是什麼。我在想像這樣的:

Parser::Parser() 
    :operations({"hello","goodbye"},{"foo","bar"}) 
{ 

} 

但這不起作用。

任何想法?

回答

1

你缺少一個初始化列表:

Parser::Parser() 
    :operations({{"hello","goodbye"},{"foo","bar"}}) 
{ 

} 

這應該工作以及:

Parser::Parser() 
    :operations{{"hello","goodbye"},{"foo","bar"}} 
{ 

} 

演示here

編輯:這是應該VS下工作的選擇:

struct a { 
    std::map<int, int> x; 

    static std::map<int, int> make_map() { 
     std::map<int, int> some_map = {{1,2}, {3,4}}; 
     return some_map; 
    } 

    a() : x(make_map()) {} 
}; 
+0

它它不喜歡這類原因。它一直在說';'預計 – thed0ctor 2013-03-17 04:50:49

+0

你使用C++ 11嗎?我已經爲我的答案添加了一個演示。 – mfontanini 2013-03-17 04:53:20

+0

是的,我在Visual Studio 2012中使用C++ 11。該網站很整潔!從來沒有見過。但是,我不確定是什麼問題。我將你的演示文件粘貼到一個空白的C++項目中,並且它有同樣的缺失';'錯誤。 – thed0ctor 2013-03-17 05:03:42