std::string swap() 方法
- 自 C++20 起
- 自 C++17 起
- C++17 之前
// Non const version only
constexpr void swap( basic_string& other ) noexcept(/* see below */);
// Non const version only
void swap( basic_string& other ) noexcept(/* see below */);
// Non-const version only
void swap( basic_string& other );
与 other
的内容进行交换。
可能失效
所有迭代器和引用都可能失效。
- 自 C++11 起
未定义行为
行为未定义
如果Allocator
不在交换时传播,并且 *this
和 other
的分配器不相等。参数
other
- 要交换内容的字符串
返回值
(无)
复杂度
常数 - O(1)。
异常
- 自 C++17 起
noexcept 规范
noexcept(std::allocator_traits<Allocator>::propagate_on_container_swap::value
|| std::allocator_traits<Allocator>::is_always_equal::value)
示例
Main.cpp
#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