function template
<vector>

std::swap (vector)

template <class T, class Alloc>  void swap (vector<T,Alloc>& x, vector<T,Alloc>& y);
交換vector的內容
交換容器xy的內容。兩個容器物件必須是同一型別(具有相同的模板引數),儘管它們的大小可能不同。

在呼叫此成員函式後,x中的元素將是呼叫前y中的元素,而y中的元素將是呼叫前x中的元素。所有迭代器、引用和指標對於被交換的物件仍然有效。

這是通用演算法swap的一個過載,它透過相互轉移其資產的所有權到另一個容器來提高效能(即,容器交換它們資料的引用,而無需實際執行任何元素複製或移動):它的行為如同x.swap(y)被呼叫。

引數

x,y
vector容器(具有相同的模板引數,TAlloc).

返回值



示例

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

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

  foo.swap(bar);

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

  std::cout << "bar contains:";
  for (std::vector<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迭代器不指向任何元素,並且可能會失效。

資料競爭

兩個容器xy都會被修改。

異常安全

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

另見