C++ <list> - clear() Function
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 example below, 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 contains:"; 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 contains:"; for(it = MyList.begin(); it != MyList.end(); ++it) cout<<" "<<*it; cout<<"\nList size is: "<<MyList.size(); return 0; }
The output of the above code will be:
Before clear() function: The list contains: 10 20 30 40 50 List size is: 5 After clear() function: The list contains: List size is: 0
❮ C++ <list> Library