Namespaces
Variants

std::set<Key,Compare,Allocator>:: operator=

From cppreference.net

set & operator = ( const set & other ) ;
(1) (自 C++26 起为 constexpr)
(2)
set & operator = ( set && other ) ;
(自 C++11 起)
(直至 C++17)
set & operator = ( set && other )
noexcept ( /* 见下文 */ ) ;
(自 C++17 起)
(自 C++26 起为 constexpr)
set & operator = ( std:: initializer_list < value_type > ilist ) ;
(3) (自 C++11 起)
(自 C++26 起为 constexpr)

替换容器中的内容。

traits std:: allocator_traits < allocator_type >

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

traits :: propagate_on_container_copy_assignment :: value true ,则 * this 的分配器将被替换为 other 分配器的副本。若赋值后 * this 的分配器与旧值比较不相等,则旧分配器将用于释放内存,随后新分配器在复制元素前用于分配内存。否则, * this 所拥有的内存可能在适当时机被复用。任何情况下,原本属于 * this 的元素可能被销毁,或被逐元素复制赋值所替换。

(since C++11)
2) 移动赋值运算符。使用移动语义将内容替换为 other 的内容(即将 other 中的数据移入此容器)。此后 other 处于有效但未指定的状态。
traits :: propagate_on_container_move_assignment :: value true ,则 * this 的分配器将被替换为 other 分配器的副本。若该值为 false * this other 的分配器比较不相等,则 * this 无法接管 other 所拥有的内存,必须逐个元素进行移动赋值操作,并根据需要使用自身的分配器分配额外内存。无论何种情况,原本属于 * this 的所有元素都会被销毁或通过逐元素移动赋值替换。
3) 将内容替换为由初始化列表 ilist 所标识的内容。

目录

参数

other - 用作数据源的另一个容器
ilist - 用作数据源的初始化列表

返回值

* this

复杂度

1) * this other 的大小呈线性关系。
2) * this 的大小成线性关系,除非分配器不相等且不传播,此时与 * this other 的大小成线性关系。
3) O(N·log(N)) 一般情况下,其中 N size ( ) + ilist. size ( ) 。若 ilist 相对于 value_comp() 已排序则为线性复杂度。

异常

2)
noexcept 规范:
noexcept ( std:: allocator_traits < Allocator > :: is_always_equal :: value
&& std:: is_nothrow_move_assignable < Compare > :: value )
(since C++17)

注释

在容器移动赋值操作后(重载 ( 2 ) ),除非因分配器不兼容而强制进行逐元素移动赋值,否则指向 other 的引用、指针和迭代器(除尾后迭代器外)仍然保持有效,但此时这些引用指向的元素已位于 * this 中。现行标准通过 [container.reqmts]/67 中的总体声明提供此保证,同时正在通过 LWG issue 2321 考虑提供更直接的保证。

示例

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

#include <initializer_list>
#include <iostream>
#include <iterator>
#include <set>
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::set<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 }

参见

构造 set
(公开成员函数)