Home > Backend Development > C++ > body text

How to Correctly Initialize a 2D `std::array` in C Using Braces?

Linda Hamilton
Release: 2024-11-24 06:22:24
Original
950 people have browsed it

How to Correctly Initialize a 2D `std::array` in C   Using Braces?

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}
};
Copy after login

This approach fails to compile, with the compiler error indicating too many initializers for std::array, 2u>. To understand why this occurs, it's crucial to know the underlying implementation of 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 } };
Copy after login

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} } } };
Copy after login

In this example:

  • "{ { {1, 2, 3} }, { { 4, 5, 6} } }" are the class braces, enclosing the initialization of the 2D array.
  • "{{1, 2, 3}, {4, 5, 6}}" are the braces for the inner C-style arrays, initializing each row of the 2D array.

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!

source:php.cn
Statement of this Website
The content of this article is voluntarily contributed by netizens, and the copyright belongs to the original author. This site does not assume corresponding legal responsibility. If you find any content suspected of plagiarism or infringement, please contact admin@php.cn
Latest Articles by Author
Popular Tutorials
More>
Latest Downloads
More>
Web Effects
Website Source Code
Website Materials
Front End Template