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)。

異常安全

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

另見