C++ 字符串库 - swap



描述

它用另一个字符串对象 str 的内容交换容器的内容。长度可能不同。

声明

以下是 std::string::swap 的声明。

void swap (string& str);

C++11

void swap (string& str);

C++14

void swap (string& str);

参数

str − 它是一个字符串对象。

返回值

异常

如果抛出异常,字符串不会发生任何更改。

示例

以下为 std::string::swap 的示例。

#include <iostream>
#include <string>

main () {
   std::string buyer ("money");
   std::string seller ("goods");

   std::cout << "Before the swap, buyer has " << buyer;
   std::cout << " and seller has " << seller << '\n';

   seller.swap (buyer);

   std::cout << " After the swap, buyer has " << buyer;
   std::cout << " and seller has " << seller << '\n';

   return 0;
}

示例输出应如下所示:

Before the swap, buyer has money and seller has goods
 After the swap, buyer has goods and seller has money
string.htm
广告