Home > Backend Development > C++ > body text

Why Do `std::vector` and `std::array` Require Different Initialization Syntaxes?

Susan Sarandon
Release: 2024-11-06 21:09:02
Original
999 people have browsed it

Why Do `std::vector` and `std::array` Require Different Initialization Syntaxes?

Why the Divergent Behavior of std::Vector and std::Array Initializer Lists?

When initializing objects of both std::vector and std::array data structures in C , a noticeable difference arises in their syntax. std::vectors can be initialized with braces, as in:

std::vector<int> x{1,2,3,4};
Copy after login

However, when it comes to std::arrays, double curly braces are required:

std::array<int, 4> y{{1,2,3,4}};
Copy after login

The reason for this discrepancy stems from the underlying nature of these data structures. std::arrays are aggregates—objects without user-defined constructors or even one explicitly taking a std::initializer_list.

Initialization with braces for std::arrays thus falls under aggregate initialization, inherited from C. In aggregate initialization, the "old style" using =: is employed:

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

This syntax allows for the elision of extra braces in "a declaration of the form T x = { a };". However, this rule does not extend to other forms of list initialization, including the one used in the second code snippet.

A CWG defect report (#1270) highlights this restriction. Should the proposed resolution be accepted, brace elision will be extended to include other list initialization forms, potentially making the following a valid syntax:

std::array<int, 4> y{ 1, 2, 3, 4 };
Copy after login

The above is the detailed content of Why Do `std::vector` and `std::array` Require Different Initialization Syntaxes?. 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
About us Disclaimer Sitemap
php.cn:Public welfare online PHP training,Help PHP learners grow quickly!