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
  • 37,241
  • 25
  • 195
  • 267
Mihai Bişog
  • 998
  • 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
  • 510,854
  • 105
  • 1,084
  • 1,005
  • 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
  • 223,805
  • 18
  • 296
  • 547