Windows7
Windows7

Reputation: 33

Multidimensional array with array class error: too many initializers

When I try to declare a multidimensional array with:

array<array<int, 7>, 5> arrayOne = {
{1, 5, 8, 0, 0, 0, 0},
{2, 3, 8, 7, 7, 0, 0},
{3, 4, 8, 2, 9, 0, 0},
{4, 8, 7, 1, 4, 0, 0},
{5, 7, 6, 8, 3, 0, 0} };

I get:

|10|error: too many initializers for 'std::array<std::array<int, 7u>, 5u>'

But when I do the same with a standard [] array:

int arrayTwo[5][7]= {
{1, 5, 8, 0, 0, 0, 0},
{2, 3, 8, 7, 7, 0, 0},
{3, 4, 8, 2, 9, 0, 0},
{4, 8, 7, 1, 4, 0, 0},
{5, 7, 6, 8, 3, 0, 0} };

I get no errors. I am using mingw g++ on Windows 7 x64. I am new to c++ and stackoverflow, your patience is appreciated.

Upvotes: 3

Views: 344

Answers (1)

πάντα ῥεῖ
πάντα ῥεῖ

Reputation: 1

For initialization std::array slightly differs from raw arrays. std::array needs to see aggregate initialization.

You have to put extra braces that the initializer value can be deduced to a std::initializer_list:

#include <array>

int main()
{
    std::array<std::array<int, 7>, 5> arrayOne = {
        { 
     // ^
          {1, 5, 8, 0, 0, 0, 0},
          {2, 3, 8, 7, 7, 0, 0},
          {3, 4, 8, 2, 9, 0, 0},
          {4, 8, 7, 1, 4, 0, 0},
          {5, 7, 6, 8, 3, 0, 0} 
        }
     // ^
    };    
}

See Live Demo

Upvotes: 7

Related Questions