C++ Standard Library C++ STL Library

C++ <vector> - assign() Function



The C++ vector::assign function is used to assign new values to the vector, replacing its old values, and modifying its size if necessary.

Syntax

//range version
template <class InputIterator>
  void assign (InputIterator first, InputIterator last);

//fill version
void assign (size_type n, const value_type& val);
//range version
template <class InputIterator>
  void assign (InputIterator first, InputIterator last);

//fill version
void assign (size_type n, const value_type& val);

//initializer list version
void assign (initializer_list<value_type> ilist);

Parameters

first Specify the starting position of InputIterator. The range used by InputIterator is [first,last).
last Specify the last position of InputIterator. The range used by InputIterator is [first,last).
n Specify new size of the vector.
val Specify the value to fill the vector with. Each of the vector will be initialized to a copy of this value.
ilist Specify the initializer_list object.

Return Value

None.

Time Complexity

Linear i.e, Θ(n)

Example:

In the example below, the vector::assign function is used to assign new values to the given vector, replacing its old values.

#include <iostream>
#include <vector>
using namespace std;
 
int main (){
  vector<int> vec1;
  vector<int> vec2;
  vector<int> vec3;

  //using fill version - size 5 with value 10
  vec1.assign(5, 10);

  //using range version 
  vector<int>::iterator it;
  it = vec1.begin();
  vec2.assign(it, it+3);  

  //using initializer list version 
  int MyList[] = {10, 20, 30, 40, 50};
  vec3.assign(MyList, MyList+3); 

  cout<<"vec1 contains: ";
  for(it = vec1.begin(); it != vec1.end(); ++it)
    cout<<*it<<" ";

  cout<<"\nvec2 contains: ";
  for(it = vec2.begin(); it != vec2.end(); ++it)
    cout<<*it<<" ";

  cout<<"\nvec3 contains: ";
  for(it = vec3.begin(); it != vec3.end(); ++it)
    cout<<*it<<" ";

  return 0;
}

The output of the above code will be:

vec1 contains: 10 10 10 10 10 
vec2 contains: 10 10 10 
vec3 contains: 10 20 30 

❮ C++ <vector> Library