名前空間
変種
操作

std::pair<T1,T2>::swap

From cppreference.com
 
 
ユーティリティライブラリ
言語サポート
型のサポート (基本型、RTTI)
ライブラリ機能検査マクロ (C++20)
プログラムユーティリティ
可変引数関数
コルーチンサポート (C++20)
契約サポート (C++26)
三方比較
(C++20)
(C++20)(C++20)(C++20)  
(C++20)(C++20)(C++20)

汎用ユーティリティ
関係演算子 (C++20で非推奨)
 
 
(1)
void swap( pair& other ) noexcept(/* 以下参照 */);
(C++11以降)
(C++20まで)
constexpr void swap( pair& other ) noexcept(/* 以下参照 */);
(C++20以降)
constexpr void swap( const pair& other ) const noexcept(/* 以下参照 */);
(2) (C++23から)

firstother.first、および secondother.second を入れ替える。これは、using std::swap; swap(first, other.first); swap(second, other.second); のように行われる。

選択された swap 関数呼び出しのいずれかが無効であるか、メンバの値が入れ替わらない場合、動作は未定義となる。

(C++23まで)
1) std::is_swappable_v<T1> または std::is_swappable_v<T2> のいずれかが true でない場合、プログラムは無効となる。
2) std::is_swappable_v<const T1> または std::is_swappable_v<const T2> のいずれかが true でない場合、プログラムは無効となる。

選択された swap 関数呼び出しのいずれかがメンバの値が入れ替わらない場合、動作は未定義となる。

(C++23から)

目次

[編集] パラメータ

その他 - 入れ替える値のペア

[編集] 戻り値

(なし)

[編集] 例外

noexcept 指定:  
noexcept(

     noexcept(swap(first, other.first)) &&
     noexcept(swap(second, other.second))

)

上記の式において、識別子swapは、C++17のstd::is_nothrow_swappableトレイトが使用するものと同じ方法で検索されます。

(C++17まで)
1)
noexcept 指定:  
noexcept(

     std::is_nothrow_swappable_v<first_type> &&
     std::is_nothrow_swappable_v<second_type>

)
2)
noexcept 指定:  
noexcept(

     std::is_nothrow_swappable_v<const first_type> &&
     std::is_nothrow_swappable_v<const second_type>

)
(C++17以降)

[編集]

#include <iostream>
#include <utility>
#include <string>
int main()
{
    std::pair<int, std::string> p1(10, "test"), p2;
    p2.swap(p1);
    std::cout << "(" << p2.first << ", " << p2.second << ")\n";
 
#if __cpp_lib_ranges_zip >= 202110L
    // Using the C++23 const qualified swap overload
    // (swap is no longer propagating pair constness)
    int i1 = 10, i2{};
    std::string s1("test"), s2;
    const std::pair<int&, std::string&> r1(i1, s1), r2(i2, s2);
    r2.swap(r1);
    std::cout << "(" << i2 << ", " << s2 << ")\n";
#endif
}

実行結果の例

(10, test)
(10, test)

[編集] 不具合報告

以下の動作変更を伴う欠陥報告が、以前に公開されたC++標準に遡って適用されました。

DR 適用対象 公開された動作 正しい動作
LWG 2456 C++11 noexcept指定が不正形式 動作するように修正

[編集] 関連項目

2つのオブジェクトの値を交換する
(関数テンプレート) [編集]
2つの tuple の内容を入れ替える
(std::tuple<Types...> の public メンバ関数) [編集]
English 日本語 中文(简体) 中文(繁體)