Home > Backend Development > C++ > body text

Why Can\'t I Use Simple Brace Initialization for 2D `std::array`s in C ?

Linda Hamilton
Release: 2024-11-21 11:51:11
Original
413 people have browsed it

Why Can't I Use Simple Brace Initialization for 2D `std::array`s in C  ?

Why is Brace Initialization Not Possible for 2D std::arrays?

In C , you can define a simple 2D array using std::array, as seen in the example:

std::array<std::array<int, 3>, 2> a = {
    {1, 2, 3},
    {4, 5, 6}
};
Copy after login

However, this initialization fails with a compiler error, stating that there are too many initializers. The reason for this discrepancy lies in the fact that std::array is an aggregate class that encapsulates a C-style array.

For proper initialization, separate braces are required for the C class and its contained C array:

std::array<std::array<int, 3>, 2> a = { {{{1, 2, 3}}, {{4, 5, 6}}} };
Copy after login

In this corrected code:

  • The outermost braces initialize the std::array class.
  • The nested braces initialize the C-style arrays within the class.

By matching the brace structure between C and C syntax, you can successfully initialize multidimensional arrays using brace initialization in C .

The above is the detailed content of Why Can\'t I Use Simple Brace Initialization for 2D `std::array`s in C ?. 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