基本上我有一个映射作为类中的成员变量,我想在基本成员初始化部分中使用键值对对它进行初始化。
Parser::Parser()
:operations() //the dictionary
{
}
我不太确定这样做的语法是什么。我在想类似的事情:
Parser::Parser()
:operations({"hello","goodbye"},{"foo","bar"})
{
}
但这行不通。
有什么想法吗?
最佳答案
您缺少初始化列表:
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()) {}
};
关于c++ - 如何在 C++ 的基本成员初始化部分中初始化 std::map?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/15457553/