名稱空間
變體
操作

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

來自 cppreference.com
< cpp‎ | 容器‎ | map
 
 
 
 
void swap( map& other );
(C++17 前)
void swap( map& other ) noexcept(/* 見下文 */);
(C++17 起)

將容器的內容與 other 的內容交換。不呼叫任何單個元素的移動、複製或交換操作。

所有迭代器和引用保持有效。end() 迭代器失效。Compare 物件必須是可交換的(Swappable),它們使用對非成員 swap 的無限定呼叫進行交換。

如果 std::allocator_traits<allocator_type>::propagate_on_container_swap::valuetrue,則分配器使用對非成員 swap 的無限定呼叫進行交換。否則,它們不被交換(並且如果 get_allocator() != other.get_allocator(),則行為未定義)。

(C++11 起)

目錄

[編輯] 引數

其他 - 用於交換內容的容器

[編輯] 異常

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>
 
// print out a 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;
}
 
// print out a container
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::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 << "──────── before swap ────────\n"
              << "m1: " << m1 << "m2: " << m2 << "ref: " << ref
              << "\niter: " << *iter << '\n';
 
    m1.swap(m2);
 
    std::cout << "──────── after swap ────────\n"
              << "m1: " << m1 << "m2: " << m2 << "ref: " << ref
              << "\niter: " << *iter << '\n';
 
    // Note that every iterator referring to an element in one container before
    // the swap refers to the same element in the other container after the swap.
    // Same is true for references.
}

輸出

──────── before swap ────────
m1: { α:alpha β:beta γ:gamma }
m2: { δ:delta ε:epsilon }
ref: α:alpha
iter: β:beta
──────── after swap ────────
m1: { δ:delta ε:epsilon }
m2: { α:alpha β:beta γ:gamma }
ref: α:alpha
iter: β:beta

[編輯] 參閱

特化 std::swap 演算法
(函式模板) [編輯]