std::pair<T1,T2>::swap
來自 cppreference.com
(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 起) |
交換 first
和 other.first
,以及 second
和 other.second
,如同透過 using std::swap; swap(first, other.first); swap(second, other.second);。
如果任一選定的 |
(直至 C++23) |
如果任一選定的 |
(C++23 起) |
目錄 |
[編輯] 引數
其他 | - | 要交換的 pair 的值 |
[編輯] 返回值
(無)
[編輯] 異常
noexcept 規範:
noexcept( noexcept(swap(first, other.first)) && 在上述表示式中,識別符號 |
(C++17 前) |
1)
noexcept 規範: noexcept( std::is_nothrow_swappable_v<first_type> && 2) noexcept 規範:
noexcept( std::is_nothrow_swappable_v<const first_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...> 的公共成員函式) |