C++ Standard Library C++ STL Library

C++ <vector> - resize() Function



The C++ vector::resize function is used to resize the container by specified number of elements (n). If n is less than the current vector size then the content is reduced to the first n elements of the vector. If n is greater than the current vector size, then the new elements are inserted at the end of the vector. 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 vector 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 vector size.

Return Value

None.

Time Complexity

Linear i.e, Θ(n).

Example:

In the example below, the vector::resize function is used to resize the vector MyVector.

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

  //size of the vector is reduced to 3
  MyVector.resize(3);

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

  //size of the vector is expanded to 8
  MyVector.resize(8);

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

  return 0;
}

The output of the above code will be:

MyVector contains: 10 20 30 100 100 0 0 0

❮ C++ <vector> Library

5