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?

2 Answers 2

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 };
Sign up to request clarification or add additional context in comments.

2 Comments

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.
Just tried this, if you want no warnings, std::array<std::array<int, 2>, 2> shape = {{ {{1, 1}}, {{1, 1}} }};. eww
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} };

2 Comments

It works however I'm wondering why my version does not. Both expressions seem equivalent on a first look.
@zoopp: No they don't. Basile uses an explicit construction, whereas you do not.

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.