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都会被修改。

异常安全

如果两个容器中的分配器进行比较相等,或者它们的 分配器特性 表明分配器应该 传播,则该函数永远不会抛出异常(无异常保证)。
否则,将导致未定义行为

另见