Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How do you initialize (through initializer lists) a multidimensional std::array in C++11?

Tags:

c++

c++11

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?

like image 972
Mihai Bişog Avatar asked Feb 29 '12 17:02

Mihai Bişog


People also ask

How to initialize an std:: array in c++?

Initialization of std::array Like arrays, we initialize an std::array by simply assigning it values at the time of declaration. For example, we will initialize an integer type std::array named 'n' of length 5 as shown below; std::array<int, 5> n = {1, 2, 3, 4, 5};

How to declare stl array in c++?

The general syntax of declaring an array container is: array<object_type, size> array_name; The above declaration creates an array container 'array_name' with size 'size' and with objects of type 'object_type'.

What is std :: initializer list?

An object of type std::initializer_list<T> is a lightweight proxy object that provides access to an array of objects of type const T .

What are initializer lists in C++?

The initializer list is used to directly initialize data members of a class. An initializer list starts after the constructor name and its parameters.


2 Answers

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 };
like image 134
kennytm Avatar answered Sep 24 '22 23:09

kennytm


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} };
like image 34
Basile Starynkevitch Avatar answered Sep 22 '22 23:09

Basile Starynkevitch