0

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;
    }
 }
Remy Lebeau
  • 555,201
  • 31
  • 458
  • 770
  • 1
    Aggregate initialization of a structure that contains an array of structures that contain an array. Does [std::array aggregate initialization requires a confusing amount of curly braces](https://stackoverflow.com/questions/29150369/stdarray-aggregate-initialization-requires-a-confusing-amount-of-curly-braces) explain? – user4581301 Mar 16 '22 at 03:38

1 Answers1

2

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 
Jason
  • 36,170
  • 5
  • 26
  • 60