std::vector<T,Allocator>:: operator=
|
vector
&
operator
=
(
const
vector
&
other
)
;
|
(1) | (自 C++20 起为 constexpr) |
| (2) | ||
|
vector
&
operator
=
(
vector
&&
other
)
;
|
(自 C++11 起)
(直至 C++17) |
|
|
vector
&
operator
=
(
vector
&&
other
)
noexcept ( /* see below */ ) ; |
(自 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
>
:
|
若 traits :: propagate_on_container_copy_assignment :: value 为 true ,则 * this 的分配器将被替换为 other 分配器的副本。若赋值后 * this 的分配器与旧值比较不相等,则旧分配器将用于释放内存,随后新分配器在复制元素前用于分配内存。否则, * this 所拥有的内存可能在适当时机被复用。任何情况下,原本属于 * this 的元素可能被销毁,或被逐元素复制赋值所替换。 |
(since C++11) |
内容参数
返回值* this 复杂度
1)
与
*
this
及
other
的大小呈线性关系。
2)
与
*
this
的大小呈线性关系,除非分配器不相等且不传播,此时与
*
this
和
other
的大小之和呈线性关系。
3)
与
*
this
和
ilist
的大小成线性关系。
异常
注解在容器移动赋值后(重载(2)),除非因分配器不兼容而强制进行逐元素移动赋值,原先引用 示例以下代码使用 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 << "Initially:\n"; print("x = ", x); print("y = ", y); print("z = ", z); std::cout << "Copy assignment copies data from x to y:\n"; y = x; print("x = ", x); print("y = ", y); std::cout << "Move assignment moves data from x to z, modifying both x and z:\n"; z = std::move(x); print("x = ", x); print("z = ", z); std::cout << "Assignment of initializer_list w to z:\n"; z = w; print("w = ", w); print("z = ", z); } 输出: Initially:
x = { 1, 2, 3 }
y = { }
z = { }
Copy assignment copies data from x to y:
x = { 1, 2, 3 }
y = { 1, 2, 3 }
Move assignment moves data from x to z, modifying both x and z:
x = { }
z = { 1, 2, 3 }
Assignment of initializer_list w to z:
w = { 4, 5, 6, 7 }
z = { 4, 5, 6, 7 }
参见
|