std::basic_string<CharT,Traits,Allocator>::swap
来自cppreference.com
< cpp | string | basic string
void swap( basic_string& other ); |
(C++17 前) | |
void swap( basic_string& other ) noexcept(/* see below */); |
(C++17 起) | |
交换 string 与 other
的内容。可能非法化所有迭代器和引用。
若 |
(C++11 起) |
参数
other | - | 要与之交换内容的 string |
返回值
(无)
异常noexcept 规定:
noexcept(std::allocator_traits<Allocator>::propagate_on_container_swap::value || std::allocator_traits<Allocator>::is_always_equal::value) |
(C++17 起) |
示例
运行此代码
#include <string> #include <iostream> int main() { std::string a = "AAA"; std::string b = "BBB"; std::cout << "before swap" << '\n'; std::cout << "a: " << a << '\n'; std::cout << "b: " << b << '\n'; a.swap(b); std::cout << "after swap" << '\n'; std::cout << "a: " << a << '\n'; std::cout << "b: " << b << '\n'; }
输出:
before swap a: AAA b: BBB after swap a: BBB b: AAA
复杂度
常数。