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
廣告