public member function
<list>

std::list::swap

void swap (list& x);
交换内容
将容器的内容与x的内容进行交换,x是同类型的另一个list。大小可能不同。

调用此成员函数后,此容器中的元素将是调用前 x 中的元素,而 x 中的元素将是调用前this容器中的元素。所有迭代器、引用和指针对于交换后的对象仍然有效。

请注意,存在一个同名的非成员函数swap,它通过一种优化重载了该算法,该优化函数的行为类似于此成员函数。

容器allocator是否也被交换未定义,除非在适当的allocator trait明确指示它们应传播的情况下。

参数

x
与此同类型的另一个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 lists
#include <iostream>
#include <list>

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

  first.swap(second);

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

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

  return 0;
}

输出
first contains: 200 200 200 200 200 
second contains: 100 100 100 


复杂度

常量。

迭代器有效性

指向两个容器中元素的的所有迭代器、指针和引用仍然有效,但现在指向另一个容器中的元素,并在其中迭代。
请注意,end iterators不指向元素,可能会失效。

数据竞争

容器和 x 都被修改。
调用该函数不会访问任何包含的元素(但请参见上面的iterator validity)。

异常安全

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

另见