c++ - std::initializer_list 的初始化

标签 c++ c++11 c++14

如何初始化无序元素的 initializer_list 复合体?
例如,考虑以下代码:

#include <unordered_map>
#include <string>

using Type = std::unordered_map<std::string, int>;
void foo(std::initializer_list<Type> l) {}

int main()
{
    Type x = {{"xxx", 0}, {"yyy", 1}};  // compile fine
    // std::initializer_list<Type> y = {{"xxx", 0}, {"yyy", 1}};
    // foo({{"xxx", 0}, {"yyy", 1}});
}

如果我取消注释第一行,我得到 (g++ 6.1.1) 错误:

error: could not convert ‘{{"xxx", 0}, {"yyy", 1}}’ from ‘’ to ‘std::initializer_list, int> >’ std::initializer_list y = {{"xxx", 0}, {"yyy", 1}};

最后,我想要做的是能够像第二个注释行一样调用 foo,它也不会编译。

最佳答案

您缺少一组 {}。你需要有

{{{"xxx", 0}}, {{"yyy", 1}}}

内部{}创建一个 std::pair<std::string, int>对于 std::inializer_list<std::pair<std::string, int>> map 是从构建的。下一级为 std::inializer_list<std::pair<std::string, int>> 创建每个 map 构建 std::initializer_list<Type> 中的每张 map .最外层{}std::initializer_list<Type> 的范围.我们可以将其扩展为

foo({{{"xxx", 0}}, {{"yyy", 1},{"zzz", 2}}});

这是一个std::initializer_list<Type>其中第一个 map 有一个条目,第二个 map 有 2 个条目。

关于c++ - std::initializer_list 的初始化,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/38961675/

相关文章:

c++ - 类型特征和未评估的上下文

c++ - 在退出或程序结束时执行函数

c++ - SDL_net UDP 包数据

c++ - 打印 Qt 变量

c++ - boost deadline_timer 最小示例 : should I substitute "sleep"?

c++ - std::allocator<T>::deallocate 的第二个参数的目的是什么?

algorithm - 使用 STL 运行长度使用 std::adjacent_find 对字符串进行编码

c++ - 在对象构造中使用 "="的影响

c++ - 将成员指针作为比较器/"key"的 std 算法

c++ - 为派生类专门化 std::hash 在 gcc 中工作,而不是 clang