Home > Article > Backend Development > Why do `std::vector` and `std::array` use different syntax for initializer lists?
When using initializer lists to initialize containers, one may have noticed a difference in syntax between std::vector and std::array. While std::vector initializes using single curly braces {}, std::array requires double curly braces {{}}. To understand why this distinction exists, we delve into the fundamental properties of these containers.
Unlike std::vector, which has user-defined constructors, std::array is considered an aggregate type. This means it lacks user-declared constructors, including those that accept initializer lists. The initialization of std::array, therefore, relies on aggregate initialization, a C feature inherited from C.
In C , aggregate initialization can be performed in two ways:
With the old style, extra braces could be elided when initializing within a declaration. However, this option is not available for direct list initialization.
CWG defect #1270 seeks to address this restriction, allowing brace elision in other forms of list initialization. If approved, the following syntax would become valid:
std::array
This change would eliminate the current disparity in syntax between std::vector and std::array, providing consistency in aggregate initialization practices.
The above is the detailed content of Why do `std::vector` and `std::array` use different syntax for initializer lists?. For more information, please follow other related articles on the PHP Chinese website!