C++ Standard Library C++ STL Library

C++ <deque> - assign() Function



The C++ deque::assign function is used to assign new values to the deque, 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 deque.
val Specify the value to fill the deque with. Each of the deque 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 deque::assign function is used to assign new values to the given deque, replacing its old values.

#include <iostream>
#include <deque>
using namespace std;
 
int main (){
  deque<int> deque1;
  deque<int> deque2;
  deque<int> deque3;

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

  //using range version 
  deque<int>::iterator it;
  it = deque1.begin();
  deque2.assign(it, it+3);  

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

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

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

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

  return 0;
}

The output of the above code will be:

deque1 contains: 10 10 10 10 10 
deque2 contains: 10 10 10 
deque3 contains: 10 20 30 

❮ C++ <deque> Library