为什么不能简单地初始化(带大括号)2D std::array? [英] Why can't simple initialize (with braces) 2D std::array?

查看:19
本文介绍了为什么不能简单地初始化(带大括号)2D std::array?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

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

我定义了简单的二维数组(3X2):

I defined simple 2D array (3X2):

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

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

I was surprised this initialization does not work, with gcc4.5 error: too many initializers for 'std::array<std::array<int, 3u>, 2u>'

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

Why can't I use this syntax?

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

I found workarounds, one very funny with extra braces, but just wonder why the first, easiest approach is not valid?

解决方法:

  // 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}
  };

[更新]

好的,感谢 KerrekSB 和评论,我明白了.因此,我的示例中的大括号似乎太少了,就像在这个 C 示例中一样:

Ok, thanks to KerrekSB and comments I get the difference. So it seems that there is too little braces in my example, like in this C example:

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

B b = {{1,2,3}};
A a = {{
     {{1,2,3}},
     {{4,5,6}}
}};

推荐答案

std::array 是一个包含 C 数组的聚合.要初始化它,你需要类本身的外大括号和 C 数组的内大括号:

std::array<T, N> is an aggregate that contains a C array. To initialize it, you need outer braces for the class itself and inner braces for the C array:

std::array<int, 3> a1 = { { 1, 2, 3 } };

将此逻辑应用于二维数组会得到:

Applying this logic to a 2D array gives this:

std::array<std::array<int, 3>, 2> a2 { { { {1, 2, 3} }, { { 4, 5, 6} } } };
//                                   ^ ^ ^ ^            ^ ^
//                                   | | | |            | |
//                                   | +-|-+------------|-+
//                                   +-|-+-|------------+---- C++ class braces
//                                     |   |
//                                     +---+--- member C array braces

这篇关于为什么不能简单地初始化(带大括号)2D std::array?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆