C++ Standard Library C++ STL Library

C++ <forward_list> - resize() Function



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.

Syntax

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

Parameters

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

None.

Time Complexity

Linear i.e, Θ(n).

Example:

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

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

  //size of the forward_list is reduced to 3
  flist.resize(3);

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

  //size of the forward_list is expanded to 8
  flist.resize(8);

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

  return 0;
}

The output of the above code will be:

flist contains: 10 20 30 100 100 0 0 0

❮ C++ <forward_list> Library