C++ List::clear() Function



The C++ std::list::clear() function is used to erase all the elements from the list( or container).

When this function is invoked the size() function returns the list size as zero. The return type of this function is void which implies that it does not return any value.

Syntax

Following is the syntax of the C++ std::list::clear() function −

void clear();

Parameters

  • It does not accepts any parameter.

Return Value

This function does not return anything.

Example 1

In the following program, we are using the C++ std::list::clear() function to clear the current list {10, 20, 30, 40, 50}.

#include<iostream>
#include<list>
using namespace std;

int main(void) {
   //create an integer list
   list<int> lst = {10, 20, 30, 40, 50};
   cout<<"The list elements are: ";
   for(int l: lst) {
      cout<<l<<" ";
   }
   cout<<"\nInitial size of list: "<<lst.size();
   //use clear() method
   lst.clear();
   cout<<"\nAfter perform the clear() function the list size is: "<<lst.size();
}

Output

The above program produces the following output −

The list elements are: 10 20 30 40 50 
Initial size of list: 5
After perform the clear() function the list size is: 0

Example 2

Following is another example of the C++ std::list::clear() function, here, we are creating a list( type char) with the value {'+', '@', '#', '$','%'}, and using this function, we are trying to clear this list.

#include<iostream>
#include<list>
using namespace std;

int main(void) {
   //create char type list
   list<char> lst = {'+', '@', '#', '$','%'};
   cout<<"The list elements are: ";
   for(char l: lst) {
      cout<<l<<" ";
   }
   cout<<"\nInitial size of list: "<<lst.size();
   //use clear() method
   lst.clear();
   cout<<"\nAfter perform the clear() function the list size is: "<<lst.size();
}

Output

Following is the output of the above program −

The list elements are: + @ # $ % 
Initial size of list: 5
After perform the clear() function the list size is: 0

Example 3

If the current list is a string type.

In this program, we create a list(type string) with the value {'Java', 'HTML', 'CSS', 'Angular'}. Then, using the C++ std::list::clear() function, we are trying to clear this list.

#include<iostream>
#include<list>
using namespace std;

int main(void) {
   list<string> lst = {"Java", "HTML", "CSS", "Angular"};
   cout<<"The list elements are: ";
   for(string l: lst) {
      cout<<l<<" ";
   }
   cout<<"\nInitial size of list: "<<lst.size();
   //use clear() method
   lst.clear();
   cout<<"\nAfter perform the clear() function the list size is: "<<lst.size();
}

Output

On executing the above program, it will produce the following output −

The list elements are: Java HTML CSS Angular 
Initial size of list: 4
After perform the clear() function the list size is: 0
Advertisements