function template
<string>

std::swap (basic_string)

template <class charT, class traits, class Alloc>  void swap (basic_string<charT,traits,Alloc>& x,             basic_string<charT,traits,Alloc>& y);
交換兩個字串的值
交換basic_string物件xy的值,使得呼叫此函式後,x的值是呼叫之前y的值,y的值是x的值。

這是泛型演算法swap的過載,它透過相互轉移對其內部資料的擁有權來提高其效能(即,字串交換對其資料的引用,而無需實際複製字元):它的行為就像x.swap(y)被呼叫。

引數

x,y
相同型別的basic_string物件(即,具有相同的模板引數,charT, 特性 (traits)Alloc).

返回值



示例

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
// swap strings
#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';

  swap (buyer,seller);

  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


複雜度

常量。

迭代器有效性

xy相關的任何迭代器、指標和引用都可能無效。

資料競爭

兩個物件,xy,都被修改。

異常安全

如果兩個字串中的分配器比較相等,或者它們的分配器特徵表明分配器應該傳播,則該函式永遠不會丟擲異常(無丟擲保證)。
否則,將導致未定義行為

另見