std::basic_string<CharT,Traits,Allocator>::swap_C++中文网

C++ 参考手册

位置:首页 > C++ 参考手册 >字符串库 >std::basic_string > std::basic_string<CharT,Traits,Allocator>::swap

交换 string 与 other 的内容。可能非法化所有迭代器和引用。

若 Allocator 不在交换时传播且 *this 与 other 的分配器不相等则行为未定义。

(C++11 èµ·)

参数

other - 要与之交换内容的 string

返回值

(无)

示例

#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

复杂度

常数。