jlc*_*lin 0 c++ initialization map initializer-list c++11
我有一个嵌套的地图,即map<int, map<int, string>>我想用初始化列表初始化.我可以使用初始化列表来初始化单级映射,但似乎无法找出嵌套映射的正确语法.它甚至可能吗?
MWE:
// This example shows how to initialize some maps
// Compile with this command:
// clang++ -std=c++11 -stdlib=libc++ map_initialization.cpp -o map_initialization
#include <iostream>
#include <map>
#include <string>
using namespace std;
int main(){
cout << "\nLearning map initialization.\n" << endl;
map<int, string> level1map = {
{1, "a"},
{2, "b"},
{3, "c"}
};
for (auto& key_value : level1map) {
cout << "key: " << key_value.first << ", value=" << key_value.second << endl;
}
// This section doesn't compile
// map<int, map<int, string>> level2map = {
// {0,
// {0, "zero"},
// {1, "one"},
// {2, "two"}
// },
// {1,
// {0, "ZERO"},
// {1, "ONE"},
// {2, "TWO"}
// }
// };
return 0;
}
Run Code Online (Sandbox Code Playgroud)
你只是在内部地图内容周围缺少一对括号:
map<int, map<int, string>> level2map = {
{0, {
{0, "zero"},
{1, "one"},
{2, "two"}
}},
{1, {
{0, "ZERO"},
{1, "ONE"},
{2, "TWO"}
}}
};
Run Code Online (Sandbox Code Playgroud)
如果你用一行写出来,也许会更加引人注目.四个列表:
{0, {0, "zero"}, {1, "one"}, {2, "two"}}
Run Code Online (Sandbox Code Playgroud)
与2件事的清单相比,第二件事是3件事的清单:
{0, {{0, "zero"}, {1, "one"}, {2, "two"}}}
Run Code Online (Sandbox Code Playgroud)