You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

C++11中如何为STL容器赋值花括号初始化列表?

Why Can We Assign Braced Initializer Lists to 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 a std::initializer_list<int> object.
  • The std::vector<int> class has a predefined operator=(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::array is 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 (so arr = {1,2,3,4} would also work).
  • Unlike std::vector, std::array can’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

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.05.20 12:33:02