Namespaces
Variants

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

From cppreference.net
Utilities library
(1)
void swap ( pair & other ) noexcept ( /* see below */ ) ;
(C++11以降)
(C++20まで)
constexpr void swap ( pair & other ) noexcept ( /* see below */ ) ;
(C++20以降)
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 the noexcept specification is ill-formed 動作するように修正

関連項目

2つのオブジェクトの値を交換する
(関数テンプレート)
2つの tuple の内容を交換する
( std::tuple<Types...> の公開メンバ関数)