Open In App

Why can't simple initialize (with braces) 2D std::array?

Last Updated : 18 Jul, 2024
Comments
Improve
Suggest changes
Like Article
Like
Report

C++ provides a fixed-size sequence container named std::array. It is a useful alternative to C-style arrays, providing additional features such as bounds checking and iterators. We can also create a 2D version of the std::array where each element is an instance of std::array itself. However, when it comes to initializing a 2D std::array, things can get a bit tricky.

Problem with Traditional Initialization of 2D std::array

Consider the following code for initializing 2D array.

C++
#include <array>
#include <iostream>

using namespace std;

int main()
{
    array<array<int, 3>, 2> my2DArray
        = { { 1, 2, 3 }, { 4, 5, 6 } };
    // Error: Braces cannot be used for direct
    // initialization of 2D std::array

    return 0;
}


Output

main.cpp: In function ‘int main()’:
main.cpp:9:38: error: too many initializers for ‘std::array, 2>’
9 | = { { 1, 2, 3 }, { 4, 5, 6 } };
|

As we can see, we tried to initialize the 2D std::array using the conventional 2d array syntax, but we got the above error.

This error is telling us that there are too many initializers for the std::array. But why? We've provided the correct number of elements, haven't we?

Why this error occurs?

The problem lies in how braces work for nested containers. When you use braces to initialize a 2D std::array, the outer braces are interpreted as an initializer list for the outer array, but the inner braces are not treated as initializer lists for the inner arrays. Instead, they are treated as aggregate initializers for the individual elements within the inner arrays.

In other words, the compiler tries to initialize each element of the outer array with an aggregate (the inner array), which is not allowed. The inner arrays themselves are not directly initialized.

Solution to the Problem

To initialize a 2D std::array, we need to use nested braces to separate the inner arrays from the outer array. Here's the correct way to do it:

C++
#include <array>
#include <iostream>

using namespace std;

int main()
{
    array<array<int, 3>, 2> my2DArray = { {
        { 1, 2, 3 }, // First inner array
        { 4, 5, 6 } // Second inner array
    } };

    // Access elements
    cout << my2DArray[0][1] << endl; // Prints 2

    return 0;
}

Output
2

By adding an extra pair of braces around the inner arrays, we ensure that each inner array is correctly initialized. Now the code compiles without errors.


Next Article
Article Tags :
Practice Tags :

Similar Reads