Facebook Page Twitter Page LinkedIn Page
× C++ Standard Library C++ STL Library

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


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


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

Return Value


Time Complexity

Linear i.e, Θ(n).


In the below example, the forward_list::resize function is used to resize the forward_list called f_list.

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

  //size of the forward_list is reduced to 3

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

  //size of the forward_list is expanded to 8

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

  return 0;

The output of the above code will be:

f_list contains: 10 20 30 100 100 0 0 0

❮ C++ - Forward List