C++ Standard Library C++ STL Library

C++ <forward_list> - clear() Function



The C++ forward_list::clear function is used to clear all elements of the forward_list. This function makes the forward_list empty and contains no elements.

Syntax

void clear() noexcept;

Parameters

No parameter is required.

Return Value

None.

Time Complexity

Linear i.e, Θ(n).

Example:

In the example below, the forward_list::clear function is used to clear all elements of 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;

  cout<<"Before clear() function: \nflist contains:";
  for(it = flist.begin(); it != flist.end(); ++it)
    cout<<" "<<*it;

  flist.clear();

  cout<<"\n\nAfter clear() function: \nflist contains:";
  for(it = flist.begin(); it != flist.end(); ++it)
    cout<<" "<<*it;

  return 0;
}

The output of the above code will be:

Before clear() function: 
flist contains: 10 20 30 40 50

After clear() function: 
flist contains:

❮ C++ <forward_list> Library