名前空間
変種
操作

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

From 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 アルゴリズムを特殊化する
(関数テンプレート) [編集]
English 日本語 中文(简体) 中文(繁體)