In this C++ tutorial, you shall learn how to copy a vector into another using Assignment Operator, with example programs.

Copy a Vector

To copy a vector into another in C++, we can use Assignment Operator. Assign the given original vector to the new vector (copy), and the expression copies the elements of the original vector to the copy.

The syntax of the statement to copy the original vector vectorX to a new copy vectorXCopy is

vectorXCopy = vectorX;

C++ Program

In the following program, we take a string vector in fruits, and copy this vector into a new vector say fruitsCopy.

main.cpp

#include <iostream>
#include <vector>
using namespace std;

int main() {
   vector<string> fruits{ "apple", "banana", "cherry" };
   vector<string> fruitsCopy = fruits;

   for(auto& element: fruitsCopy) {
      cout << element << endl;
   }
}

Output

apple
banana
cherry
ADVERTISEMENT

Conclusion

In this C++ Tutorial, we learned how to copy a given vector into another vector, using Assignment Operator.