List::clear() in C++ STL


In this article we will be discussing the working, syntax and examples of list::clear() function in C++.

What is a List in STL?

List is a data structure that allows constant time insertion and deletion anywhere in sequence. Lists are implemented as doubly linked lists. Lists allow non-contiguous memory allocation. List perform better insertion extraction and moving of element in any position in container than array, vector and deque. In List the direct access to the element is slow and list is similar to forward_list, but forward list objects are single linked lists and they can only be iterated forwards.

What is clea()?

list::clear() is an inbuilt function in C++ STL which is declared in header file. list::clear(), clears the whole list. In other words the clear() removes all the elements present in the list container and leaves the container with size 0.

Syntax

list_name.clear();

This function accepts no parameter.

Return Value

This function returns nothing, just removes all the elements from the container.

Example

In the below code we will insert the elements into the list and after that we will apply the clear function to clear the entire list making it empty.

 Live Demo

#include <iostream>
#include <list>
using namespace std;
int main(){
   list<int> myList = { 10, 20, 30, 40, 50 };
   cout<<"List before applying clear() function";
   for (auto i = myList.begin(); i != myList.end(); ++i)
   cout << ' ' << *i;
   //applying clear() function to clear the list
   myList.clear();
   for (auto i = myList.begin(); i!= myList.end(); ++i)
      cout << ' ' << *i;
   cout<<"\nlist is cleared ";
   return 0;
}

Output

If we run the above code then it will generate the following output

List before applying clear() function 10 20 30 40 50
list is cleared

Example

In the below code we will clear the entire list using clear() function and after that we will reinsert the new elements to the list and display the same.

 Live Demo

#include <iostream>
#include <list>
using namespace std;
int main (){
   list<int> myList;
   std::list<int>::iterator i;
   myList.push_back (10);
   myList.push_back (20);
   myList.push_back (30);
   cout<<"List before applying clear() function";
   for (auto i = myList.begin(); i != myList.end(); ++i)
      cout << ' ' << *i;
   myList.clear();
   for (auto i = myList.begin(); i!= myList.end(); ++i)
   cout << ' ' << *i;
   cout<<"\nlist is cleared ";
   myList.push_back (60);
   myList.push_back (70);
   cout<<"\nelements in my list are: ";
   for (auto i=myList.begin(); i!=myList.end(); ++i)
      cout<< ' ' << *i;
   return 0;
}

If we run the above code then it will generate the following output

List before applying clear() function 10 20 30 40 50
list is cleared
Elements in my list are : 60 70

Updated on: 26-Feb-2020

4K+ Views

Kickstart Your Career

Get certified by completing the course

Get Started
Advertisements