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

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

Linda Hamilton
Linda HamiltonOriginal
2024-11-21 11:51:11411browse

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}
};

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}}} };

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!

Statement:
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