【问题标题】:Nested map bracket initialization fails to compile嵌套地图括号初始化无法编译
【发布时间】:2014-09-19 01:39:46
【问题描述】:

展示问题的微小、非常简单的代码示例:

#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 }},
};

错误? main.cpp:4:58: No matching constructor for initialization of 'std::map&lt;std::string, std::map&lt;std::string, int&gt; &gt;'

【问题讨论】:

  • 我的编译器 (g++) 给出了一个类似(但更详细)的错误,归结为“无法从初始化列表转换为映射”...我不知道为什么会发生错误不过。

标签: c++ c++11 map


【解决方案1】:

你需要一副额外的牙套:

#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 }}},
//                                        ^                              ^
};

这与初始化外部映射的方式基本相同 - 内部映射需要使用初始化列表进行初始化 - 一对大括号 - 包含映射的键值对的初始化列表 - 另一对大括号元素。

正如 Matt McNabb 所说,您不必显式构造 std::strings。

【讨论】:

  • 很有趣,而且完全不明显。感谢您的帮助。
  • 注意std::string有隐式构造函数,所以你也可以放{ "string 1", {{ "string 2", 0 }} }
  • @LulzCop std::map 条目由键值对初始化。它不会自动将键之后的所有内容分组到一组值初始化器中,您必须将其标记为关闭。
  • @MattMcNabb 我知道,这只是为了防止有人认为问题在于编译器更喜欢 c-strings 而不是 std::string,正如我展示的一个人所想的那样。
猜你喜欢
  • 1970-01-01
  • 2023-04-10
  • 1970-01-01
  • 2017-01-05
  • 2021-01-28
  • 2018-05-09
  • 2020-08-19
  • 2019-06-25
  • 2017-07-24
相关资源
最近更新 更多