相关疑难解决方法(0)

为什么std :: vector和std :: array的C++ initializer_list行为不同?

码:

std::vector<int> x{1,2,3,4};
std::array<int, 4> y{{1,2,3,4}};
Run Code Online (Sandbox Code Playgroud)

为什么我需要std :: array的双花括号?

c++ stl c++11

67
推荐指数
2
解决办法
5149
查看次数

为什么不能简单地初始化(带括号)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++ ×2

c++11 ×2

stl ×2

initialization ×1