function template
<forward_list>

std::swap (forward_list)

template <class T, class Alloc>  void swap (forward_list<T,Alloc>& x, forward_list<T,Alloc>& y);
交換兩個 forward_list 容器的內容
容器x的內容與容器y的內容進行交換。兩個容器物件必須是相同的型別(相同的模板引數),儘管大小可能不同。

呼叫此成員函式後,x中的元素將是呼叫前y中的元素,而y中的元素將是呼叫前x中的元素。所有迭代器、引用和指標對於被交換的物件都保持有效。

這是通用演算法 swap 的一個過載,它透過相互轉移其資產給另一個容器來提高效能(即,容器交換它們資料的引用,而不實際執行任何元素複製或移動):它的行為就好像x.swap(y)被呼叫。

引數

lhs,rhs
相同型別的 forward_list 容器(即,具有相同的模板引數,TAlloc).

返回值



示例

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
// swap (forward_list overload)
#include <iostream>
#include <forward_list>

int main ()
{
  std::forward_list<int> first = {10, 20, 30};
  std::forward_list<int> second = {100, 200};
  std::forward_list<int>::iterator it;

  swap(first,second);

  std::cout << "first contains:";
  for (int& x: first) std::cout << ' ' << x;
  std::cout << '\n';

  std::cout << "second contains:";
  for (int& x: second) std::cout << ' ' << x;
  std::cout << '\n';

  return 0;
}

輸出
first contains: 100 200
second contains: 10 20 30


複雜度

常量。

迭代器有效性

指向兩個容器中元素的的所有迭代器、指標和引用仍然有效,但現在指向另一個容器中的元素,並在其中迭代。
請注意,結束迭代器(包括 before_begin)不指向任何元素,並且可能會失效。

資料競爭

兩個容器xy都會被修改。

異常安全

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

另見