14

To create a 2D array with std::vector, you'd do

vector<vector<int>> array2d = {{1, 2,  3,  4},
                               {5, 6,  7,  8},
                               {9, 10, 11, 12}};

The outer {} represent the outer vector; the inner {}, inner vector.

However, to create a 2D array with std::array, you'd need to do

array<array<int,4>, 3> array2d = {{{1, 2,  3,  4},
                                   {5, 6,  7,  8},
                                   {9, 10, 11, 12}}};

Why does std::array of std::arrays need an extra pair of enclosing {}?

ruohola
  • 21,987
  • 6
  • 62
  • 97
codepro
  • 283
  • 3
  • 8
  • 5
    For a vector `{ ... }` is an `std::initializer_list` which will be passed to the correct [`std::vector` constructor](https://en.cppreference.com/w/cpp/container/vector). Since [`std::array`](https://en.cppreference.com/w/cpp/container/array) is an *aggregate* the outer `{}` pair is for the outer array object initialization. The middle `{}` pair is for the outer *array* and the inner `{}` pairs are for the inner arrays. – Some programmer dude Jul 18 '20 at 20:08
  • 1
    See also [Why is the C++ initializer_list behavior for std::vector and std::array different?](https://stackoverflow.com/questions/11400090/why-is-the-c-initializer-list-behavior-for-stdvector-and-stdarray-differen) – ggorlen Jul 18 '20 at 22:46

0 Answers0