Skip to content
Related Articles

Related Articles

list::clear() in C++ STL
  • Last Updated : 15 Jan, 2018


Lists are containers used in C++ to store data in a non contiguous fashion, Normally, Arrays and Vectors are contiguous in nature, therefore the insertion and deletion operations are costlier as compared to the insertion and deletion option in Lists.

list::clear()

clear() function is used to remove all the elements of the list container, thus making it size 0.
Syntax :

listname.clear()
Parameters :
No parameters are passed.
Result :
All the elements of the list are
removed ( or destroyed )

Examples:

Input  : list{1, 2, 3, 4, 5};
         list.clear();
Output : list{}

Input  : list{};
         list.clear();
Output : list{}

Errors and Exceptions

1. It has a no exception throw guarantee.
2. Shows error when a parameter is passed.




// CPP program to illustrate
// Implementation of clear() function
#include <iostream>
#include <list>
using namespace std;
  
int main()
{
    list<int> mylist{ 1, 2, 3, 4, 5 };
  
    mylist.clear();
    // List becomes empty
  
    // Printing the list
    for (auto it = mylist.begin(); it != mylist.end(); ++it)
        cout << ' ' << *it;
    return 0;
}

Output:

No Output

Related Article : Delete elements in C++ STL List

Want to learn from the best curated videos and practice problems, check out the C++ Foundation Course for Basic to Advanced C++ and C++ STL Course for foundation plus STL.  To complete your preparation from learning a language to DS Algo and many more,  please refer Complete Interview Preparation Course.
My Personal Notes arrow_drop_up
Recommended Articles
Page :