名稱空間
變體
操作

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

來自 cppreference.com
< cpp‎ | utility‎ | pair
 
 
 
 
(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 起)

目錄

[編輯] 引數

其他 - 要交換的 pair 的值

[編輯] 返回值

(無)

[編輯] 異常

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++ 標準。

缺陷報告 應用於 釋出時的行為 正確的行為
LWG 2456 C++11 noexcept 規範格式錯誤 已修復

[編輯] 參閱

交換兩個物件的值
(函式模板) [編輯]
交換兩個 tuple 的內容
(std::tuple<Types...> 的公共成員函式) [編輯]