std::unordered_set<Key,Hash,KeyEqual,Allocator>::operator=

来自cppreference.com

 
 
容器库
序列
(C++11)
关联
无序关联
适配器
视图
(C++20)
 
 
unordered_set& operator=( const unordered_set& other );
(1) (C++11 起)
(2)
unordered_set& operator=( unordered_set&& other );
(C++11 起)
(C++17 前)
unordered_set& operator=( unordered_set&& other ) noexcept(/* see below */);
(C++17 起)
unordered_set& operator=( std::initializer_list<value_type> ilist );
(3) (C++11 起)

替换容器内容。

1) 复制赋值运算符。以 other 的副本替换内容。
std::allocator_traits<allocator_type>::propagate_on_container_copy_assignment::valuetrue ,则用 other 的分配器的副本替换 *this 的分配器。若 *this 的分配器在赋值后将与其旧值比较不相等,则用旧分配器解分配内存,然后在复制元素前用新分配器分配内存。否则,在可行时可能复用 *this 所拥有的内存。任何情况下,原属于 *this 的元素要么被销毁,要么被逐元素复制赋值替换。
2) 移动赋值运算符。用移动语义以 other 的内容替换内容(即从 other 移动 other 中的数据到此容器中)。之后 other 在合法但未指定的状态。
std::allocator_traits<allocator_type>::propagate_on_container_move_assignment::valuetrue ,则用 other 的分配器的副本替换 *this 的分配器。若它为 false*thisother 的分配器不比较相等,则 *this 不能接管 other 所拥有的内存的所有权且必须单独地移动赋值每个元素,并用其自身的分配器按需分配额外内存。任何情况下,原属于 *this 的元素要么被销毁,要么被逐元素移动赋值替换。
3) 以 initializer_list ilist 所标识者替换内容。

参数

other - 用作数据源的另一容器
ilist - 用作数据源的 initializer_list

返回值

*this

复杂度

1)*thisother 的大小成线性。
2)*this 的大小成线性,除非分配器不比较相等且不传播,该情况下与 *thisother 的大小成线性。
3)*thisilist 的大小成线性。

异常

可能抛出实现定义的异常。

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

&& std::is_nothrow_move_assignable<Hash>::value

&& std::is_nothrow_move_assignable<Pred>::value)
(C++17 起)

注解

在容器移动赋值(重载 (2) )后,除非不兼容的分配器强制逐元素移动赋值,指向 other 的引用及迭代器(除了尾迭代器)保持合法,但指代现于 *this 中的元素。当前标准由 [container.requirements.general]/12 中的总括陈述作出此保证,而 LWG 2321 正在考虑更严格的保证。

示例

下列代码用 operator= 赋值一个 std::unordered_set 给另一个:

#include <unordered_set>
#include <iostream>
 
void display_sizes(const std::unordered_set<int> &nums1,
                   const std::unordered_set<int> &nums2,
                   const std::unordered_set<int> &nums3)
{
    std::cout << "nums1: " << nums1.size() 
              << " nums2: " << nums2.size()
              << " nums3: " << nums3.size() << '\n';
}
 
int main()
{
    std::unordered_set<int> nums1 {3, 1, 4, 6, 5, 9};
    std::unordered_set<int> nums2; 
    std::unordered_set<int> nums3;
 
    std::cout << "Initially:\n";
    display_sizes(nums1, nums2, nums3);
 
    // 复制赋值从 nums1 复制数据到 nums2
    nums2 = nums1;
 
    std::cout << "After assigment:\n"; 
    display_sizes(nums1, nums2, nums3);
 
    // 移动赋值从 nums1 移动数据到 nums3,
    // 一同修改 nums1 和 nums3
    nums3 = std::move(nums1);
 
    std::cout << "After move assigment:\n"; 
    display_sizes(nums1, nums2, nums3);
}

输出:

Initially:
nums1: 6 nums2: 0 nums3: 0
After assigment:
nums1: 6 nums2: 6 nums3: 0
After move assigment:
nums1: 0 nums2: 6 nums3: 6

参阅

构造 unordered_set
(公开成员函数)