【问题标题】:Initialization of std::initializer_liststd::initializer_list 的初始化
【发布时间】:2016-12-22 01:09:10
【问题描述】:

如何初始化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) 错误:

错误:无法将'{{"xxx", 0}, {"yyy", 1}}'从''转换为'std::initializer_list, int> >' std::initializer_list y = {{"xxx", 0}, {"yyy", 1}};

最后,我想做的是能够像第二条注释行一样调用foo,这也无法编译。

【问题讨论】:

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

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


【解决方案1】:

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

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

内部{} 为构建地图的std::inializer_list&lt;std::pair&lt;std::string, int&gt;&gt; 创建了一个std::pair&lt;std::string, int&gt;。下一个级别为std::inializer_list&lt;std::pair&lt;std::string, int&gt;&gt; 创建每个映射以在std::initializer_list&lt;Type&gt; 中构建每个映射。最外面的{}std::initializer_list&lt;Type&gt; 的范围。我们可以将其扩展为

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

这是一个std::initializer_list&lt;Type&gt;,其中第一个映射有一个条目,第二个映射有2个。

【讨论】:

    【解决方案2】:

    您缺少一些大括号。 {{"xxx", 0}, {"yyy", 1}}Type 的一个很好的初始化器,但对于仅包含一个 unordered_mapTypes 列表,您需要

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

    或者对于包含两个unordered_maps 的Types 列表,每个@s 有一对,

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

    【讨论】:

      【解决方案3】:

      在第 2 行,您尝试初始化 std::unordered_map 的 std::initializer_list,但您只给它提供了 unordered_map 的参数。添加另一组大括号将解决此问题。

      #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
          //initialization for std::unordered_map<std::string, int>
          // std::initializer_list<Type> y = {{"xxx", 0}, {"yyy", 1}}; 
      
          //correct initialization, each std::unordered_map has exactly 1 element in it
          std::initializer_list<Type> y = { {{"xxx", 0}}, {{"yyy", 1}}}
      
          // foo({{"xxx", 0}, {"yyy", 1}}); //As before
          foo({{{"xxx", 0}}, {"yyy", 1}}}); //Correct call
      }
      

      【讨论】:

        猜你喜欢
        • 1970-01-01
        • 1970-01-01
        • 2018-01-13
        • 2019-04-16
        • 2015-09-04
        • 1970-01-01
        • 2020-01-19
        • 1970-01-01
        • 1970-01-01
        相关资源
        最近更新 更多