为什么不能简单初始化(用大括号)2D std :: array? [英] Why can't simple initialize (with braces) 2D std::array?
问题描述
可能重复:
c ++为什么initializer_list对std :: vector和std :: array的行为是不同的
我定义了简单的2D数组(3X2):
I defined simple 2D array (3X2):
std::array<std::array<int,3>,2> a {
{1,2,3},
{4,5,6}
};
我很惊讶这个初始化不工作,用gcc4.5错误: '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}
};
[UPDATE]
好的,谢谢到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< T,N>
是包含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屋!