C++ Standard Library C++ STL Library

C++ <list> - resize() Function



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

Return Value

None.

Time Complexity

Linear i.e, Θ(n).

Example:

In the example below, the list::resize function is used to resize the list called MyList.

#include <iostream>
#include <list>
using namespace std;
 
int main (){
  list<int> MyList{10, 20, 30, 40, 50};
  list<int>::iterator it;

  //size of the list is reduced to 3
  MyList.resize(3);

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

  //size of the list is expanded to 8
  MyList.resize(8);

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

  return 0;
}

The output of the above code will be:

MyList contains: 10 20 30 100 100 0 0 0

❮ C++ <list> Library