14

I am trying to initialize a 2D std::array trough initializer lists however the compiler tells me that there are too many initializers.

e.g.:

std::array<std::array<int, 2>, 2> shape = { {1, 1},
                                            {1, 1} };

Compiler error: error: too many initializers for ‘std::array<std::array<int, 2ul>, 2ul>’

But clearly there aren't too many. Am I doing something wrong?

Cœur
  • 34,719
  • 24
  • 185
  • 251
Mihai Bişog
  • 978
  • 9
  • 24

2 Answers2

14

Try to add one more pair {} to ensure we're initializing the internal C array.

std::array<std::array<int, 2>, 2> shape = {{ {1, 1},
                                             {1, 1} }};

Or just drop all the brackets.

std::array<std::array<int, 2>, 2> shape = { 1, 1,
                                            1, 1 };
kennytm
  • 491,404
  • 99
  • 1,053
  • 989
  • It always feels like an abstraction leak to me that we have to do that. Just a result of the library not being "internal" to the language, but built _with_ it, I suppose. – Lightness Races in Orbit Mar 08 '12 at 13:30
  • 1
    Just tried this, if you want no warnings, `std::array, 2> shape = {{ {{1, 1}}, {{1, 1}} }};`. eww – Jeff Sep 29 '12 at 03:37
7

I would suggest (without even have trying it, so I could be wrong)

typedef std::array<int, 2> row;
std::array<row,2> shape = { row {1,1}, row {1,1} };
Basile Starynkevitch
  • 216,767
  • 17
  • 275
  • 509