Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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.

like image 729
Windows7 Avatar asked Jul 19 '26 14:07

Windows7


1 Answers

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

like image 131
πάντα ῥεῖ Avatar answered Jul 21 '26 02:07

πάντα ῥεῖ