我有一个像这样的类
class MapClass {
public:
static map<string, map<string, double>> spreadMap;
};
既然可以这样初始化一个标准映射:
map<string,int> AnotherClass::standardMap = {
{"A",0},
{"B",1},
{"C",2}
};
我试着对2D-Map做同样的事情:
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> >'
有谁知道如何解决这个问题,如果可能的话,没有某种初始化函数。
非常感谢!
事实上,你已经在你的帖子中找到了解决方案。
您向我们展示的标准简单映射初始化是
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
这里有一个现场演示。(顺便说一下,这里不需要=
。)