Why can't simple initialize (with braces) 2D std::array?
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
PiotrNycz
I registered in SO to ask question. The answers were of surprisingly good quality, so I decided to stay. I am Software Architect and Code Guard (aka Component Guardian) in big telecommunication company. See my github for some freely available projects
Updated on July 09, 2022Comments
-
PiotrNycz almost 2 years
Possible Duplicate:
c++ why initializer_list behavior for std::vector and std::array are differentI defined simple 2D array (3X2):
std::array<std::array<int,3>,2> a { {1,2,3}, {4,5,6} };
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?
Workarounds:
// 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]
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}} }};