嵌套的地图括号初始化无法编译

Lul*_*Cop 4 c++ map c++11

一个简单,非常简单的代码示例,展示了这个问题:

#include <string>
#include <map>

static std::map<std::string, std::map<std::string, int>> defaults = {
    { std::string("Definitely a string"), { std::string("This too"), 0 }},
};
Run Code Online (Sandbox Code Playgroud)

错误? main.cpp:4:58: No matching constructor for initialization of 'std::map<std::string, std::map<std::string, int> >'

T.C*_*.C. 8

你需要额外的一对括号:

#include <string>
#include <map>

static std::map<std::string, std::map<std::string, int>> defaults = {
    { std::string("Definitely a string"), {{ std::string("This too"), 0 }}},
//                                        ^                              ^
};
Run Code Online (Sandbox Code Playgroud)

它与初始化外部地图的方式基本相同 - 内部地图需要使用初始化列表初始化 - 一对括号 - 包含地图键值对的初始化列表 - 每个元素的另一对括号.

正如Matt McNabb所说,你不必明确地构建std::strings.