C++ Vector 库 - vector() 函数
描述
C++ 移动构造函数 std::vector::vector() 使用 move 语义构造具有 other 内容的容器。
如果未提供 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

