命名空间
变体
操作

std::deque<T,Allocator>::operator=

来自 cppreference.cn
< cpp‎ | 容器‎ | deque
 
 
 
 
deque& operator=( const deque& other );
(1)
(2)
deque& operator=( deque&& other );
(C++11 起)
(C++17 前)
deque& operator=( deque&& other ) noexcept(/* see below */);
(C++17 起)
deque& operator=( std::initializer_list<value_type> ilist );
(3) (C++11 起)

替换容器的内容。

1) 复制赋值运算符。用 `other` 内容的副本替换内容。

如果 std::allocator_traits<allocator_type>::propagate_on_container_copy_assignment::valuetrue,则 *this 的分配器被替换为 other 的副本。如果赋值后 *this 的分配器与旧值比较不相等,则先使用旧分配器解除分配内存,然后使用新分配器分配内存,最后复制元素。否则,*this 所拥有的内存尽可能被重用。无论如何,最初属于 *this 的元素可能被销毁或被逐个元素复制赋值替换。

(C++11 起)
2) 移动赋值运算符。使用移动语义(即将 other 中的数据从 other 移动到此容器中)替换内容。之后 other 处于有效但未指定的状态。
如果 std::allocator_traits<allocator_type>::propagate_on_container_move_assignment::valuetrue,则 *this 的分配器被替换为 other 的分配器的副本。如果为 false*thisother 的分配器比较不相等,则 *this 不能取得 other 拥有的内存所有权,并且必须逐个元素进行移动赋值,根据需要使用自己的分配器分配额外内存。无论如何,所有最初属于 *this 的元素要么被销毁,要么被逐个元素移动赋值替换。
3) 用初始化列表 ilist 标识的内容替换内容。

目录

[编辑] 参数

其他 - 另一个容器,用作数据源
ilist - 初始化列表,用作数据源

[编辑] 返回值

*this

[编辑] 复杂度

1) 与 `*this` 和 `other` 的大小呈线性关系。
2) 线性于 *this 的大小,除非分配器不相等且不传播,在这种情况下线性于 *thisother 的大小。
3)*thisilist 的大小呈线性关系。

[编辑] 异常

1-3) 可能抛出实现定义的异常。
(C++17 前)
1,3) 可能抛出实现定义的异常。
2)
noexcept 规范:  
noexcept(std::allocator_traits<Allocator>::is_always_equal::value)
(C++17 起)

[编辑] 注意

容器移动赋值(重载 (2))后,除非不兼容的分配器强制进行逐元素移动赋值,否则对 other 的引用、指针和迭代器(除了尾迭代器)仍然有效,但指向现在位于 *this 中的元素。当前标准通过 [container.reqmts]/67 中的笼统声明做出此保证,并且正在通过 LWG issue 2321 考虑更直接的保证。

[编辑] 示例

以下代码使用 operator= 将一个 std::deque 赋值给另一个

#include <initializer_list>
#include <iostream>
#include <iterator>
#include <deque>
 
void print(auto const comment, auto const& container)
{
    auto size = std::size(container);
    std::cout << comment << "{ ";
    for (auto const& element : container)
        std::cout << element << (--size ? ", " : " ");
    std::cout << "}\n";
}
 
int main()
{
    std::deque<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 }

[编辑] 参阅

构造 deque
(public member function) [edit]
将值赋给容器
(public member function) [edit]