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


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

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

  f_list.clear();

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

  return 0;
}

The output of the above code will be:

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

After clear() function: 
f_list contains:

❮ C++ - Forward List