Home  >  Article  >  Backend Development  >  Why do `std::vector` and `std::array` use different syntax for initializer lists?

Why do `std::vector` and `std::array` use different syntax for initializer lists?

Patricia Arquette
Patricia ArquetteOriginal
2024-11-08 12:18:02726browse

Why do `std::vector` and `std::array` use different syntax for initializer lists?

Understanding the Different Initializer_list Behavior for std::vector and std::array

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.

std::array: An Aggregate

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.

Aggregate Initialization in C

In C , aggregate initialization can be performed in two ways:

  1. Old Style: Utilizing the =: syntax, e.g., std::array y = {{1, 2, 3, 4}};
  2. Direct List Initialization: Directly passing an initializer list, e.g., std::array y{1, 2, 3, 4};

With the old style, extra braces could be elided when initializing within a declaration. However, this option is not available for direct list initialization.

A Forthcoming Change

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 y{1, 2, 3, 4};

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!

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