跳到主要内容

std::string swap() 方法

// Non const version only
constexpr void swap( basic_string& other ) noexcept(/* see below */);

other 的内容进行交换。

可能失效

所有迭代器引用都可能失效。

未定义行为

行为未定义

如果 Allocator 不在交换时传播,并且 *thisother 的分配器不相等。

参数

  • other - 要交换内容的字符串

返回值

(无)

复杂度

常数 - O(1)

异常

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
本文源自此 CppReference 页面。它可能为了改进或编辑者偏好而进行了更改。点击“编辑此页面”可查看此文档的所有更改。
悬停查看原始许可证。

std::string swap() 方法

// Non const version only
constexpr void swap( basic_string& other ) noexcept(/* see below */);

other 的内容进行交换。

可能失效

所有迭代器引用都可能失效。

未定义行为

行为未定义

如果 Allocator 不在交换时传播,并且 *thisother 的分配器不相等。

参数

  • other - 要交换内容的字符串

返回值

(无)

复杂度

常数 - O(1)

异常

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
本文源自此 CppReference 页面。它可能为了改进或编辑者偏好而进行了更改。点击“编辑此页面”可查看此文档的所有更改。
悬停查看原始许可证。