'why is 1 extra bracket needed for the initializer list [duplicate]
I have been reading a book called "C++ How To Program" by Paul and Harvey Deitel. I am stuck at page 357 because if I follow the book and try putting only {{ }} instead of {{{ }}}, I will receive an error:
too many initializers for 'std::array<std::array<int, 2>, 3>'
Why do I need to put 1 extra set of brackets in the initializer list? For example, if I tried to put only {{1,2},{3,4},{5,6}} instead of {{{1,2},{3,4},{5,6}}} I will get an error.
int main()
{
array<array<int, 2>, 3> a {{1,2},{3,4},{5,6}};
for(auto const& i : a)
{
for(auto const& j : i)
{
std::cout << j << '\t';
}
std::cout << std::endl;
}
}
Solution 1:[1]
From std::array
's documentation
This container is an aggregate type with the same semantics as a struct holding a C-style array
T[N]
as its only non-static data member.
This in turn means that, we will need outer braces for the class type itself and then inner braces for the C style T[n]
array.
Now lets apply this to your case of 2D array:
// v----------------------------> needed for inner C style array
array<array<int, 2>, 3> a { { {1,2},{3,4},{5,6} } };
// ^------------------------------> needed for class type itself
Sources
This article follows the attribution requirements of Stack Overflow and is licensed under CC BY-SA 3.0.
Source: Stack Overflow
Solution | Source |
---|---|
Solution 1 |