當前位置: 首頁>>編程示例 >>用法及示例精選 >>正文


C++ Vector vector()用法及代碼示例


描述

C++ 移動構造函數std::vector::vector()使用 other using 的內容構造容器移動語義。

如果分配未提供,分配器由 move-construction 從屬於 other 的分配器中獲取。

聲明

以下是移動構造函數 std::vector::vector() 形式 std::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

相關用法


注:本文由純淨天空篩選整理自 C++ Vector Library - vector() Function。非經特殊聲明,原始代碼版權歸原作者所有,本譯文未經允許或授權,請勿轉載或複製。