C++11中如何为STL容器赋值花括号初始化列表?
std::array and std::vector in C++11 (Beyond Initialization)? Great question! This behavior comes down to two key C++11 features built specifically to make container handling more intuitive: std::initializer_list and enhanced aggregate assignment. Let’s break this down for each container using your example code.
For std::vector
std::vector (along with most other STL containers like std::list or std::unordered_map) got an overloaded assignment operator in C++11 that accepts a std::initializer_list<T>. Here’s what’s happening in your line vec = {4, 3, 2, 1};:
- When you write
{4, 3, 2, 1}, the compiler automatically converts this braced list into astd::initializer_list<int>object. - The
std::vector<int>class has a predefinedoperator=(std::initializer_list<int>)that replaces the vector’s current elements with the ones from the initializer list. This includes resizing the vector if the new list has a different length, then copying or moving elements into place.
For std::array
std::array is a fixed-size aggregate type (think of it as a C-style array wrapped in a lightweight struct). C++11 extended aggregate assignment rules to allow using braced initializer lists directly for assignment:
arr = {{1, 2, 3, 4}};
- Since
std::arrayis an aggregate, the assignment uses aggregate initialization logic. The outer braces are technically required to match the struct wrapper, but most compilers let you omit them for convenience (soarr = {1,2,3,4}would also work). - Unlike
std::vector,std::arraycan’t resize, so the number of elements in the braced list must exactly match the array’s size—otherwise you’ll get a compile error. The assignment simply copies each element from the list into the internal fixed-size array.
Let’s Verify With Your Code
Here’s a quick walkthrough of how your example leverages these features:
#include <iostream> #include <array> #include <vector> using namespace std; int main() { array<int, 4> arr; vector<int> vec(4); arr = {{1, 2, 3, 4}}; // Uses C++11 aggregate assignment for std::array vec = {4, 3, 2, 1}; // Calls vector's initializer_list-based assignment operator cout << "arr: "; for (auto elem : arr) cout << elem << " "; cout << "\nvec: "; for (auto elem : vec) cout << elem << "..."; }
Before C++11, neither of these assignments would have been valid—braced initializer lists were only allowed during variable initialization, not for post-creation assignment.
内容的提问来源于stack exchange,提问作者digilur

