This post will discuss how to copy a vector in C++. Copying a vector includes constructing a new vector with a copy of each of the elements in the original vector and in the same order.

1. Using Copy Constructor

The recommended approach is to use the copy constructor, which internally takes care of all copying.

Download  Run Code

 
We can also use a range constructor for this:

2. Using vector::operator=

Here, the idea is to create an empty vector and use its member function operator= for copying all elements of the given vector to it.

Download  Run Code

 
We know that an object is passed by value to a function in C++ by default. That means the stack will create the copy of the whole object if the object is passed by value. We can take advantage of this fact and force a copy of the vector, as shown below:

3. Using std::copy function

The standard algorithm for copying is std::copy. We can use it for copying elements from the source vector to the destination vector. But make sure that the destination vector has sufficient space to accommodate all elements of the source sequence.

Download  Run Code

 
If the destination vector doesn’t have enough space for copying, prefer using std::back_insert iterator, which will call vector::push_back on the destination vector, as shown below:

Download  Run Code

4. Using vector::insert function

The vector class has a standard function, insert(), that can insert elements from a specified range.

Download  Run Code

5. Using vector::assign function

Here’s another solution using the public member function assign() of the vector class, which replaces the vector contents with contents of the specified range.

Download  Run Code

6. Using vector::push_back function

Finally, we can call vector::push_back on each of the elements in the given vector using a range-based for-loop. Simple yet efficient.

Download  Run Code

 
Important Note:

Please note that all above solutions perform a shallow copy on the vector object. C++ doesn’t offer any utility function for performing a deep copy. If a deep copy is needed, we can write our own routine, which traverses the vector and manually copy the references to other objects.

That’s all about copying a vector in C++.