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,則該函式絕不會丟擲異常(無丟擲保證)。
否則,將導致未定義行為

另見