相关疑难解决方法(0)

为什么不能简单地初始化(带括号)2D std :: array?

可能重复:
c ++为什么std :: vector和std :: array的initializer_list行为不同

我定义了简单的2D数组(3X2):

  std::array<std::array<int,3>,2> a {
    {1,2,3},
    {4,5,6}
  };
Run Code Online (Sandbox Code Playgroud)

我很惊讶这个初始化不起作用,用gcc4.5错误: too many initializers for 'std::array<std::array<int, 3u>, 2u>'

为什么我不能使用这种语法?

我找到了解决方法,一个非常有趣的额外括号,但只是想知道为什么第一个,最简单的方法是无效的?

解决方法:

  // EXTRA BRACES
  std::array<std::array<int,3>,2> a {{
    {1,2,3},
    {4,5,6}
  }};

  // EXPLICIT CASTING
  std::array<std::array<int,3>,2> a {
    std::array<int,3>{1,2,3},
    std::array<int,3>{4,5,6}
  };
Run Code Online (Sandbox Code Playgroud)

[UPDATE]

好的,感谢KerrekSB和评论,我得到了不同.所以在我的例子中似乎有太少的括号,就像在这个C例子中一样:

struct B {
  int array[3];
};
struct A {
  B array[2];
};

B b = {{1,2,3}};
A a = {{
     {{1,2,3}},
     {{4,5,6}}
}};
Run Code Online (Sandbox Code Playgroud)

c++ stl initialization c++11

31
推荐指数
1
解决办法
2万
查看次数

标签 统计

c++ ×1

c++11 ×1

initialization ×1

stl ×1