C++ Vector Library - vector() Function



Description

The C++ move constructor std::vector::vector() constructs the container with the contents of other using move semantics.

If alloc is not provided, allocator is obtained by move-construction from the allocator belonging to other.

Declaration

Following is the declaration for move costructor std::vector::vector() form std::vector header.

C++11

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

Parameters

x − Another vector container of same type.

Return value

Constructor never returns value.

Exceptions

This member function never throws exception.

Time complexity

Linear i.e. O(n)

Example

The following example shows the usage of move constructor 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;
}

Let us compile and run the above program, this will produce the following result −

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
Advertisements