Namespaces
Variants

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

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

汎用ユーティリティ
関係演算子 (C++20で非推奨)
整数比較関数
(C++20)(C++20)(C++20)    
(C++20)
Swap および 型操作
(C++14)
(C++11)
(C++11)
(C++11)
(C++17)
共通語彙型
(C++11)
(C++17)
(C++17)
(C++17)
(C++11)
(C++17)
(C++23)



 
 
void swap( pair& other ) noexcept(/* see below */);
(1) (C++11以降)
(C++20以降 constexpr)
constexpr void swap( const pair& other ) const noexcept(/* see below */);
(2) (C++23以降)

first を other.first と、second を other.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以降)

パラメータ

other - 交換する値のペア

例外

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
    // C++23 const修飾されたswapオーバーロードの使用
    // (swapはpairのconst性を伝播しなくなりました)
    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...> の公開メンバ関数)