C++向量庫 - swap() 函式



描述

C++函式std::vector::swap()交換兩個向量的內容。

宣告

以下是來自std::vector標頭檔案的std::vector::swap()函式宣告。

template <class T, class Alloc>
void swap (vector<T,Alloc>& v1, vector<T,Alloc>& v2);

引數

  • v1 − 第一個向量容器。

  • v2 − 第二個向量容器。

返回值

無。

異常

此函式從不丟擲異常。

時間複雜度

線性,即O(1)

示例

以下示例顯示了std::vector::swap()函式的用法。

#include <iostream>
#include <vector>

using namespace std;

int main(void) {
   vector<int> v1 = {1, 2, 3, 4, 5};
   vector<int> v2 = {10, 20, 30};

   cout << "Contents of vector v1 before swap operation" << endl;
   for (int i = 0; i < v1.size(); ++i)
      cout << v1[i] << endl;

   cout << "Contents of vector v2 before swap operation" << endl;
   for (int i = 0; i < v2.size(); ++i)
      cout << v2[i] << endl;

   swap(v1, v2);
   cout << "Contents of vector v1 after swap operation" << endl;
   for (int i = 0; i < v1.size(); ++i)
      cout << v1[i] << endl;

   cout << "Contents of vector v2 after swap operation" << endl;
   for (int i = 0; i < v2.size(); ++i)
      cout << v2[i] << endl;

   return 0;
}

讓我們編譯並執行上面的程式,這將產生以下結果:

Contents of vector v1 before swap operation
1
2
3
4
5
Contents of vector v2 befor swap operation
10
20
30
Contents of vector v1 after swap operation
10
20
30
Contents of vector v2 after swap operation
1
2
3
4
5
vector.htm
廣告
© . All rights reserved.