[英]C++: Initialization of a 2D static map
I have a class looking like this 我有一个看起来像这样的班级
class MapClass {
public:
static map<string, map<string, double>> spreadMap;
};
So since it is possible to initialize a standard map like this: 因此,由于可以像这样初始化标准地图:
map<string,int> AnotherClass::standardMap = {
{"A",0},
{"B",1},
{"C",2}
};
I've tried to do the same to the 2D-Map: 我试图对2D地图做同样的事情:
map<string, map<string, double>> MapClass::spreadMap = {
{"A", {"B", 0}},
{"C", {"D", 1}},
{"E", {"F", 2}}
};
But apparently it is not working. 但显然它不起作用。 The Error Message is: 错误消息是:
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> >'
Does anyone know how to solve this problem, if possible without some kind of initializing-function. 没有人知道如何解决这个问题,如果可能的话,没有某种初始化功能。
Thank you very much! 非常感谢你!
In fact you have already the solution in your post. 实际上,您已经在帖子中找到了解决方案。
The standard simple map initilisation that you showed us is 您向我们展示的标准简单地图初始化为
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
But in the complex map you write (I added the comments): 但是在复杂的地图中,您编写了代码(我添加了评论):
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
As you can see, when you compare the inner map initialization with your previous working code, there is an inconsistency : the surrounding braces for of the initializer list of the inner map. 如您所见,在将内部映射初始化与先前的工作代码进行比较时,存在一个不一致:内部映射的初始化列表的大括号。 How would you write it if the inner map should be initialized with several elements ? 如果内部映射应使用几个元素初始化,您将如何编写?
The solution would be to add the missing braces : 解决方案是添加缺少的括号:
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
Here a live demo . 这里有现场演示 。 ( By the way, you don't need the =
here. ) ( 顺便说一句,您不需要=
。 )
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.