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


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

Syntax

void clear();
void clear() noexcept;

Parameters

No parameter is required.

Return Value

None.

Time Complexity

Linear i.e, Θ(n)

Example:

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

  cout<<"Before clear() function: \nThe list is:";
  for(it = MyList.begin(); it != MyList.end(); ++it)
    cout<<" "<<*it;
  cout<<"\nList size is: "<<MyList.size()<<"\n\n";

  MyList.clear();

  cout<<"After clear() function: \nThe list is:";
  for(it = MyList.begin(); it != MyList.end(); ++it)
    cout<<" "<<*it;
  cout<<"\nList size is: "<<MyList.size()<<"\n\n";
  return 0;
}

The output of the above code will be:

Before clear() function: 
The list is: 10 20 30 40 50
List size is: 5

After clear() function: 
The list is:
List size is: 0

❮ C++ - List