74

In C++, how do I create a multidimensional std::array? I've tried this:

std::array<std::array<int, 3>, 3> arr = {{5, 8, 2}, {8, 3, 1}, {5, 3, 9}};

But it doesn't work. What am I doing wrong and how do I fix this?

LazySloth13
  • 2,087
  • 7
  • 26
  • 36
  • This is an issue that causes some confusion. See the comments to the answer to the duplicate. I am not convinced that your code is really illegal in C++11, but it is not clear-cut. – juanchopanza Jul 20 '13 at 07:19
  • That actually should compile I think? The extra braces can be elided. – Rapptz Jul 20 '13 at 07:20
  • 5
    Note that there is a [c++14 proposal](http://www.open-std.org/JTC1/SC22/WG21/docs/papers/2013/n3526.html) to fix this. – Jesse Good Jul 20 '13 at 07:21
  • @Rapptz I think they can be elided, I also think (but that isn't as clear) that they shouldn't be needed in the first place. – juanchopanza Jul 20 '13 at 07:21

1 Answers1

84

You need extra brackets, until c++14 proposal kicks in.

std::array<std::array<int, 3>, 3> arr = {{{5, 8, 2}, {8, 3, 1}, {5, 3, 9}}};
billz
  • 41,716
  • 7
  • 75
  • 95
  • 18
    Can anyone tell, what does every of all these 3 levels of braces means? And why does also work this: `... = {{ {{5, 8, 2}}, {{...}}, ... }}` (4 levels of braces)? – user1234567 Dec 22 '14 at 18:55
  • 5
    @user3241228 my guess: inner=array, next=array-of-arrays, last=uniform initialization. In your example, you have a 3d array, where the middle rank just happens to have a single element (and that element is a 3-int array). – Alex Shroyer Nov 13 '16 at 20:16
  • 1
    The extra brackets are still necessary in C++17. https://godbolt.org/z/8ejr37 – alfC Mar 16 '21 at 07:00