Namespaces
Variants

std::unordered_map<Key,T,Hash,KeyEqual,Allocator>:: swap

From cppreference.net

void swap ( unordered_map & other ) ;
(自 C++11 起)
(直至 C++17)
void swap ( unordered_map & other ) noexcept ( /* 见下文 */ ) ;
(自 C++17 起)
(自 C++26 起为 constexpr)

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

所有迭代器和引用保持有效。 end() 迭代器会失效。 Hash KeyEqual 必须满足 可交换要求 ,且这些类型的对象通过非成员函数 swap 进行无条件交换。 若 std:: allocator_traits < allocator_type > :: propagate_on_container_swap :: value true ,则分配器通过非成员函数 swap 进行无条件交换。否则分配器不会被交换(且若 get_allocator ( ) ! = other. get_allocator ( ) ,则行为未定义)。

目录

参数

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

异常

Hash KeyEqual 对象的交换操作抛出的任何异常。

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

&& std:: is_nothrow_swappable < Hash > :: value

&& std:: is_nothrow_swappable < key_equal > :: value )
(C++17 起)

复杂度

常量。

示例

#include <iostream>
#include <string>
#include <utility>
#include <unordered_map>
// 打印 std::pair
template<class Os, class U, class V>
Os& operator<<(Os& os, const std::pair<U, V>& p)
{
    return os << p.first << ':' << p.second;
}
// 打印容器
template<class Os, class Co>
Os& operator<<(Os& os, const Co& co)
{
    os << '{';
    for (const auto& i : co)
        os << ' ' << i;
    return os << " }\n";
}
int main()
{
    std::unordered_map<std::string, std::string>
        m1{{"γ", "gamma"}, {"β", "beta"}, {"α", "alpha"}, {"γ", "gamma"}},
        m2{{"ε", "epsilon"}, {"δ", "delta"}, {"ε", "epsilon"}};
    const auto& ref = *(m1.begin());
    const auto iter = std::next(m1.cbegin());
    std::cout << "──────── 交换前 ────────\n"
              << "m1: " << m1 << "m2: " << m2 << "ref: " << ref
              << "\niter: " << *iter << '\n';
    m1.swap(m2);
    std::cout << "──────── 交换后 ────────\n"
              << "m1: " << m1 << "m2: " << m2 << "ref: " << ref
              << "\niter: " << *iter << '\n';
    // 注意:交换前指向一个容器中元素的每个迭代器,在交换后会指向另一个容器中的相同元素。
    // 引用也是如此。
}

可能的输出:

──────── 交换前 ────────
m1: { α:alpha β:beta γ:gamma }
m2: { δ:delta ε:epsilon }
ref: α:alpha
iter: β:beta
──────── 交换后 ────────
m1: { δ:delta ε:epsilon }
m2: { α:alpha β:beta γ:gamma }
ref: α:alpha
iter: β:beta

参见

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