std::vector<T,Allocator>::operator=
来自cppreference.com
vector& operator=( const vector& other ); |
(1) | (C++20 起为 constexpr ) |
(2) | ||
vector& operator=( vector&& other ); |
(C++11 起) (C++17 前) |
|
vector& operator=( vector&& other ) noexcept(/* 见下文 */); |
(C++17 起) (C++20 起为 constexpr ) |
|
vector& operator=( std::initializer_list<value_type> ilist ); |
(3) | (C++11 起) (C++20 起为 constexpr ) |
替换容器内容。
设 traits
为 std::allocator_traits<allocator_type>:
1) 复制赋值运算符。以 other 内容的副本替换内容。
如果 traits::propagate_on_container_copy_assignment::value 是 true,那么用 other 的分配器的副本替换 *this 的分配器。如果 *this 的分配器在赋值后将与其旧值比较不相等,那么用旧分配器解分配内存,然后在复制元素前用新分配器分配内存。否则,在可行时可能复用 *this 所拥有的内存。任何情况下,原属于 *this 的元素要么被销毁,要么被逐元素复制赋值所替换。 |
(C++11 起) |
2) 移动赋值运算符。用移动语义以 other 的内容替换内容(即从 other 移动 other 中的数据到此容器中)。之后 other 处于合法但未指定的状态。
如果 traits::propagate_on_container_move_assignment::value 是 true,那么用 other 的分配器的副本替换 *this 的分配器。如果它是 false 且 *this 与 other 的分配器比较不相等,那么 *this 不能接管 other 所拥有的内存的所有权且必须单独地移动赋值每个元素,并用其自身的分配器按需分配额外内存。任何情况下,原属于 *this 的元素要么被销毁,要么被逐元素移动赋值所替换。
3) 以初始化器列表 ilist 所标识者替换内容。
目录 |
[编辑] 参数
other | - | 用作数据源的另一容器 |
ilist | - | 用作数据源的初始化器列表 |
[编辑] 返回值
*this
[编辑] 复杂度
1) 与 *this 和 other 的大小成线性。
2) 与 *this 的大小成线性,除非分配器比较不相等且不传播,该情况下与 *this 和 other 的大小成线性。
3) 与 *this 和 ilist 的大小成线性。
[编辑] 异常
2)
noexcept 说明:
noexcept(std::allocator_traits<Allocator>::propagate_on_container_move_assignment::value || std::allocator_traits<Allocator>::is_always_equal::value) |
(C++17 起) |
[编辑] 注解
在容器移动赋值(重载 (2))后,除非不兼容的分配器强制逐元素移动赋值,指向 other 的引用及迭代器(除了尾迭代器)保持合法,但将指代现于 *this 中的元素。当前标准由 [container.requirements.general]/12 中的总括陈述作出此保证,而 LWG 问题 2321 正在考虑更严格的保证。
[编辑] 示例
以下代码使用 operator= 从一个 std::vector 赋值给另一个:
运行此代码
#include <initializer_list> #include <iostream> #include <iterator> #include <vector> void print(const auto comment, const auto& container) { auto size = std::size(container); std::cout << comment << "{ "; for (const auto& element : container) std::cout << element << (--size ? ", " : " "); std::cout << "}\n"; } int main() { std::vector<int> x{1, 2, 3}, y, z; const auto w = {4, 5, 6, 7}; std::cout << "初始状态:\n"; print("x = ", x); print("y = ", y); print("z = ", z); std::cout << "复制赋值将数据从 x 复制到 y:\n"; y = x; print("x = ", x); print("y = ", y); std::cout << "移动赋值将数据从 x 移动到 z,同时修改 x 和 z:\n"; z = std::move(x); print("x = ", x); print("z = ", z); std::cout << "将 initializer_list w 赋给 z:\n"; z = w; print("w = ", w); print("z = ", z); }
输出:
初始状态: x = { 1, 2, 3 } y = { } z = { } 复制赋值将数据从 x 复制到 y: x = { 1, 2, 3 } y = { 1, 2, 3 } 移动赋值将数据从 x 移动到 z,同时修改 x 和 z: x = { } z = { 1, 2, 3 } 将 initializer_list w 赋给 z: w = { 4, 5, 6, 7 } z = { 4, 5, 6, 7 }
[编辑] 参阅
构造 vector (公开成员函数) | |
将值赋给容器 (公开成员函数) |