Henk
Henk

Reputation: 846

Initializer lists for multidimensional arrays and vectors

I want to use initializer lists for my vectors and arrays. Ultimately, I would like to initialize an array of vectors of some class A, but I do not get there while getting weird compiler errors. Here is some code:

#include <vector>
#include <array>

class A {
    public:
        A(int x_, int y_): x(x_), y(y_) {}
    private:
        int x;
        int y;
};

int main() {
    auto data = std::array<int, 3>{0, 1, 2};
    auto data2 = std::array<A, 3>{ A(0,0), A(1,1), A(2,2) };
    auto data3 = std::vector<std::vector<int>> { {0,0,0}, {1,1,1}, {2,2,2} };
    auto data4 = std::array<std::vector<int>, 3> { {0,0,0}, {1,1,1}, {2,2,2} };
  //auto data5 = std::array<std::vector<A>, 3> { ??? };
}

The first three examples work perfectly fine. I do not get why the forth example does not compile (using c++17) as it is exactly the same as in the third example. The error is "too many initializer" which I do not get. Everything I tried for the fifth example does not work. Is it even possible?

Upvotes: 1

Views: 247

Answers (1)

Vlad from Moscow
Vlad from Moscow

Reputation: 311088

Use one more pair of braces.

auto data4 = std::array<std::vector<int>, 3> { { {0,0,0}, {1,1,1}, {2,2,2} } };

Otherwise the first list {0,0,0} is considered as an initializer of the whole object of the type std::array<std::vector<int>, 3 >..

std::array is an aggregate. From the C++ 14 Standard (23.3.2.1 Class template array overview)

2 An array is an aggregate (8.5.1) that can be initialized with the syntax

array<T, N> a = { initializer-list }; 

where initializer-list is a comma-separated list of up to N elements whose types are convertible to T.

Upvotes: 2

Related Questions