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



描述

C++ 移動建構函式 std::vector::vector() 使用移動語義構造包含其他內容的容器。移動語義。

如果alloc未提供,則分配器透過從屬於 other 的分配器移動構造獲得。

宣告

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

C++11

vector (vector&& x);
vector (vector&& x, const allocator_type& alloc);

引數

x − 另一個相同型別的向量容器。

返回值

建構函式永不返回值。

異常

此成員函式永不丟擲異常。

時間複雜度

線性,即 O(n)

示例

以下示例演示了移動建構函式 std::vector::vector() 的用法。

#include <iostream>
#include <vector>

using namespace std;

int main(void) {
   /* create fill constructor */
   vector<int> v1(5, 123);

   cout << "Elements of vector v1 before move constructor" << endl;
   for (int i = 0; i < v1.size(); ++i)
      cout << v1[i] << endl;

   /* create constructor using move semantics */
   vector<int> v2(move(v1));

   cout << "Elements of vector v1 after move constructor" << endl;
   for (int i = 0; i < v1.size(); ++i)
      cout << v1[i] << endl;

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

   return 0;
}

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

Elements of vector v1 before move constructor
123
123
123
123
123
Elements of vector v1 after move constructor
Element of vector v2
123
123
123
123
123
vector.htm
廣告