function template
<list>

std::swap (list)

template <class T, class Alloc>  void swap (list<T,Alloc>& x, list<T,Alloc>& y);
交换两个list的内容
容器x的内容与y的内容进行交换。两个容器对象必须是相同的类型(相同的模板参数),但大小可能不同。

调用此成员函数后,x中的元素将是调用前y中的元素,而y中的元素将是调用前x中的元素。所有迭代器、引用和指针在交换后的对象中保持有效。

这是通用算法swap的一个重载,它通过相互转移对它们资产的所有权到另一个容器来提高性能(即,容器交换数据的引用,而不实际执行任何元素复制或移动):它的行为就好像x.swap(y)被调用。

参数

x,y
同类型的list容器(即,具有相同的模板参数,TAlloc).

返回值



示例

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

int main ()
{
  std::list<int> foo (3,100);   // three ints with a value of 100
  std::list<int> bar (5,200);   // five ints with a value of 200

  std::swap(foo,bar);

  std::cout << "foo contains:";
  for (std::list<int>::iterator it = foo.begin(); it!=foo.end(); ++it)
    std::cout << ' ' << *it;
  std::cout << '\n';

  std::cout << "bar contains:";
  for (std::list<int>::iterator it = bar.begin(); it!=bar.end(); ++it)
    std::cout << ' ' << *it;
  std::cout << '\n';

  return 0;
}

输出
foo contains: 200 200 200 200 200 
bar contains: 100 100 100 


复杂度

常量。

迭代器有效性

指向两个容器中元素的任何迭代器、指针和引用在调用后仍然有效,并且现在指向它们在调用前所指向的相同元素,但在另一个容器中,它们现在是迭代的。
请注意,end iterators 不指向元素,可能会失效。

数据竞争

两个容器xy都会被修改。

异常安全

如果两个list对象中的分配器比较相等,或者它们的allocator traits指示分配器应propagate,则该函数绝不会抛出异常(无抛出保证)。
否则,将导致未定义行为

另见