std::swap(std::basic_string)
來自 cppreference.com
< cpp | string | basic_string
定義於標頭檔案 <string> |
||
template< class CharT, class Traits, class Alloc > void swap( std::basic_string<CharT, Traits, Alloc>& lhs, |
(C++17 前) | |
template< class CharT, class Traits, class Alloc > void swap( std::basic_string<CharT, Traits, Alloc>& lhs, |
(C++17 起) (C++20 起為 constexpr) |
|
為 std::basic_string 特化 std::swap 演算法。交換 lhs 和 rhs 的內容。
等價於 lhs.swap(rhs)。
目錄 |
[編輯] 引數
lhs, rhs | - | 要交換內容的字串 |
[編輯] 返回值
(無)
[編輯] 複雜度
常數時間。
異常noexcept 規範:
noexcept(noexcept(lhs.swap(rhs))) |
(C++17 起) |
[編輯] 示例
執行此程式碼
#include <iostream> #include <string> int main() { std::string a = "AAA"; std::string b = "BBBB"; std::cout << "Before swap:\n" "a = " << a << "\n" "b = " << b << "\n\n"; std::swap(a, b); std::cout << "After swap:\n" "a = " << a << "\n" "b = " << b << '\n'; }
輸出
Before swap: a = AAA b = BBBB After swap: a = BBBB b = AAA
[編輯] 缺陷報告
下列更改行為的缺陷報告追溯地應用於以前出版的 C++ 標準。
缺陷報告 | 應用於 | 釋出時的行為 | 正確的行為 |
---|---|---|---|
LWG 2064 | C++11 | 非成員 swap 是 noexcept 的,與成員 swap 不一致。 |
noexcept 已移除 |
[編輯] 亦參見
交換內容 (public member function) |