C++ Standard Library C++ STL Library

C++ <deque> - resize() Function



The C++ deque::resize function is used to resize the container by specified number of elements (n). If n is less than the current deque size then the content is reduced to the first n elements of the deque. If n is greater than the current deque size, then the new elements are inserted at the end of the deque. If val is specified, then new elements are initialized with val, else they are value-initialized.

Syntax

void resize (size_type n, value_type val = value_type());
void resize (size_type n);
void resize (size_type n, const value_type& val);

Parameters

n Specify new deque size expressed in terms of number of element in it.
val Specify value for the added elements in case that n is greater than current deque size.

Return Value

None.

Time Complexity

Linear i.e, Θ(n).

Example:

In the example below, the deque::resize function is used to resize the deque MyDeque.

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

  //size of the deque is reduced to 3
  MyDeque.resize(3);

  //size of the deque is expanded to 5 with val=100
  MyDeque.resize(5, 100);

  //size of the deque is expanded to 8
  MyDeque.resize(8);

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

  return 0;
}

The output of the above code will be:

MyDeque contains: 10 20 30 100 100 0 0 0

❮ C++ <deque> Library