Initialization of 2D std::array with Braces
While working with C , initializing a 2D std::array using braces can be challenging. The following code snippet illustrates the issue:
std::array<std::array<int, 3>, 2> a { {1, 2, 3}, {4, 5, 6} };
This approach fails to compile, with the compiler error indicating too many initializers for std::array
std::array Internals
std::array is an aggregate that encompasses a C-style array. Hence, to initialize it correctly, it requires outer braces for the class itself and inner braces for the C array member:
std::array<int, 3> a1 = { { 1, 2, 3 } };
Extending this logic to a 2D array results in the following valid initialization:
std::array<std::array<int, 3>, 2> a2 { { { {1, 2, 3} }, { { 4, 5, 6} } } };
In this example:
The above is the detailed content of How to Correctly Initialize a 2D `std::array` in C Using Braces?. For more information, please follow other related articles on the PHP Chinese website!