当前位置: 首页>>编程示例 >>用法及示例精选 >>正文


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。非经特殊声明,原始代码版权归原作者所有,本译文未经允许或授权,请勿转载或复制。