VOOZH about

URL: https://www.geeksforgeeks.org/cpp/vector-operator-in-cpp-stl/

⇱ Vector Operator = in C++ STL - GeeksforGeeks


  • Courses
  • Tutorials
  • Interview Prep

Vector Operator = in C++ STL

Last Updated : 23 Jul, 2025

In C++, the vector operator = is used to assign the contents of one vector to another. It allows you to copy elements from one vector to another or initialize a vector with another vector's contents.

Let’s take a look at a simple code example:


Output
1 2 3 5 4 

Explanation: The contents of vector v1 are copied to vector v2. After the assignment, v2 contains the same elements as v1.

This article covers the syntax, usage, and common examples of vector operator = in C++:

Syntax of Vector operator =

v2 = v1;

The destination vector (left operand) will be modified to contain the same elements as the source vector (right operand).

Note: The containers should be of same types, an error is thrown. 

Examples of Vector operator =

The below examples demonstrate the common usage of the vector operator = in C++.

Assign One Vector to Another


Output
1 2 3 5 4 

Replace a Vector


Output
1 2 3 

Assign an Empty Vector


Output
v1 is now empty.
Comment
Article Tags: