std::multimap<Key,T,Compare,Allocator>::swap

来自cppreference.com
< cpp‎ | container‎ | multimap

 
 
 
 
void swap( multimap& other );
(C++17 前)
void swap( multimap& other ) noexcept(/* 见下文 */);
(C++17 起)

将内容与 other 的交换。不在单独的元素上调用任何移动、复制或交换操作。

所有迭代器和引用保持有效。end() 迭代器会失效。

Pred 对象必须可交换 (Swappable) ,并用非成员 swap 的非限定调用交换它们。

如果 std::allocator_traits<allocator_type>::propagate_on_container_swap::valuetrue,那么就会用对非成员 swap 的无限定调用交换分配器。否则,不交换它们(且在 get_allocator() != other.get_allocator() 时行为未定义)。

(C++11 起)

参数

other - 要与之交换内容的容器

返回值

(无)

异常

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

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

复杂度

常数。

示例

#include <iostream>
#include <string>
#include <utility>
#include <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 (auto const& i : co)
        os << ' ' << i;
    return os << " }\n";
}
 
int main()
{
    std::multimap<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 << "──────── swap 之前 ────────\n"
              << "m1:" << m1 << "m2:" << m2 << "引用:" << ref
              << "\n迭代器:" << *iter << '\n';
 
    m1.swap(m2);
 
    std::cout << "──────── swap 之后 ────────\n"
              << "m1:" << m1 << "m2:" << m2 << "引用:" << ref
              << "\n迭代器:" << *iter << '\n';
 
    // 注意交换前指代一个容器中的元素的每个迭代器在交换后都指代同一元素。对于引用也是这样。
}

输出:

──────── swap 之前 ────────
m1:{ α:alpha β:beta γ:gamma γ:gamma }
m2:{ δ:delta ε:epsilon ε:epsilon }
引用:α:alpha
迭代器:β:beta
──────── swap 之后 ────────
m1:{ δ:delta ε:epsilon ε:epsilon }
m2:{ α:alpha β:beta γ:gamma γ:gamma }
引用:α:alpha
迭代器:β:beta


参阅

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