Facebook Page Twitter Page LinkedIn Page
× C++ Standard Library C++ STL Library


The C++ vector::operator= function is used to assign new content to the container by replacing the current content and adjusting the container size accordingly.

Syntax

//copies all elements of x into the container
vector& operator= (const vector& x);
//copy version - copies all elements
//of x into the container
vector& operator= (const vector& x);

//move version - moves elements of x
//into the container
vector& operator= (vector&& x);

//initializer list version - copies all 
//elements of il into the container
vector& operator= (initializer_list<value_type> il);

Parameters

x Specify a vector object of same type.
il Specify an initializer_list object.

Return Value

Returns *this.

Time Complexity

Linear i.e, Θ(n).

Example: Using copy version

In the below example, the vector::operator= function is used to assign new values to the given vector.

#include <iostream>
#include <vector>
using namespace std;
 
int main (){
  vector<int> vec1{10, 20, 30, 40, 50};

  //copying all content of vec1 into vec2
  vector<int> vec2;
  vec2 = vec1;

  cout<<"The vec1 contains:";
  for(int i = 0; i < vec1.size(); i++)
    cout<<" "<<vec1[i];

  cout<<"\nThe vec2 contains:";
  for(int i = 0; i < vec2.size(); i++)
    cout<<" "<<vec2[i];

  return 0;
}

The output of the above code will be:

The vec1 contains: 10 20 30 40 50
The vec2 contains: 10 20 30 40 50

Example: Using move version

Using the move version of operator=, the content of one vector can be moved to another vector. Consider the following example:

#include <iostream>
#include <vector>
using namespace std;
 
int main (){
  vector<int> vec1{10, 20, 30, 40, 50};

  cout<<"The vec1 contains:";
  for(int i = 0; i < vec1.size(); i++)
    cout<<" "<<vec1[i];

  //moving all content of vec1 into vec2
  vector<int> vec2;
  vec2 = move(vec1);

  cout<<"\nThe vec1 contains:";
  for(int i = 0; i < vec1.size(); i++)
    cout<<" "<<vec1[i];

  cout<<"\nThe vec2 contains:";
  for(int i = 0; i < vec2.size(); i++)
    cout<<" "<<vec2[i];

  return 0;
}

The output of the above code will be:

The vec1 contains: 10 20 30 40 50
The vec1 contains:
The vec2 contains: 10 20 30 40 50

Example: Using initializer list version

The initializer list can also be used to assign values into a vector container. Consider the below example:

#include <iostream>
#include <vector>
using namespace std;
 
int main (){
  //creating empty vector
  vector<int> vec;

  //creating initializer list
  initializer_list<int> ilist = {10, 20, 30, 40, 50};

  //assigning values of vec using ilist
  vec = ilist;

  cout<<"The vec contains:";
  for(int i = 0; i < vec.size(); i++)
    cout<<" "<<vec[i];

  return 0;
}

The output of the above code will be:

The vec contains: 10 20 30 40 50

❮ C++ - Vector