Namespaces
Variants

std::set<Key,Compare,Allocator>:: swap

From cppreference.net

void swap ( set & other ) ;
(C++17 前)
void swap ( set & other ) noexcept ( /* 见下文 */ ) ;
(C++17 起)
(C++26 起为 constexpr)

交换容器的内容与 other 的内容。不会对单个元素调用任何移动、复制或交换操作。

所有迭代器和引用保持有效。 end() 迭代器会失效。 Compare 必须满足 可交换 要求,且该类型的对象通过非成员函数 swap 进行不限定的调用交换。

std:: allocator_traits < allocator_type > :: propagate_on_container_swap :: value true ,则通过非限定调用非成员函数 swap 来交换分配器。否则不交换分配器(且若 get_allocator ( ) ! = other. get_allocator ( ) ,则行为未定义)。

(since C++11)

目录

参数

其他 - 用于交换内容的容器

异常

Compare 对象交换抛出的任何异常。

(C++17 前)
noexcept 规范:
noexcept ( std:: allocator_traits < Allocator > :: is_always_equal :: value
&& std:: is_nothrow_swappable < Compare > :: value )
(C++17 起)

复杂度

常量。

示例

#include <functional>
#include <iostream>
#include <set>
template<class Os, class Co>
Os& operator<<(Os& os, const Co& co)
{
    os << '{';
    for (const auto& i : co)
        os << ' ' << i;
    return os << " } ";
}
int main()
{
    std::set<int> a1{3, 1, 3, 2}, a2{5, 4, 5};
    auto it1 = std::next(a1.begin());
    auto it2 = std::next(a2.begin());
    const int& ref1 = *(a1.begin());
    const int& ref2 = *(a2.begin());
    std::cout << a1 << a2 << *it1 << ' ' << *it2 << ' ' << ref1 << ' ' << ref2 << '\n';
    a1.swap(a2);
    std::cout << a1 << a2 << *it1 << ' ' << *it2 << ' ' << ref1 << ' ' << ref2 << '\n';
    // 注意:交换前指向一个容器中元素的每个迭代器,在交换后会指向另一个容器中的相同元素。引用也是如此。
    struct Cmp : std::less<int>
    {
        int id{};
        Cmp(int i) : id{i} {}
    };
    std::set<int, Cmp> s1{{2, 2, 1, 1}, Cmp{6}}, s2{{4, 4, 3, 3}, Cmp{9}};
    std::cout << s1 << s2 << s1.key_comp().id << ' ' << s2.key_comp().id << '\n';
    s1.swap(s2);
    std::cout << s1 << s2 << s1.key_comp().id << ' ' << s2.key_comp().id << '\n';
    // 因此,比较器对象(Cmp)在交换后也会被交换。
}

输出:

{ 1 2 3 } { 4 5 } 2 5 1 4
{ 4 5 } { 1 2 3 } 2 5 1 4
{ 1 2 } { 3 4 } 6 9
{ 3 4 } { 1 2 } 9 6

参见

特化 std::swap 算法
(函数模板)