In C++, std::list::clear() removes all elements from a std::list. Every node is unlinked and destroyed, and the list becomes empty.
The list object itself stays alive. You can add new elements to it right after the call. Include <list> to use it.
This is a member of std::list<T>, a doubly linked list. Every element lives in its own node with a link to the previous and the next node, so a list can insert and erase anywhere quickly once you hold an iterator. It has no access by index, so l[i] does not exist.
Syntax
Call clear with empty brackets on any list you want to empty.
C++
l.clear(); // l is now empty
bool e = l.empty(); // true
std::size_t n = l.size(); // 0
Call
What it does
l.clear()
Erases every element. Afterwards size() is 0 and empty() is true.
If you only want to erase some elements, use erase(), remove(), or pop_back() instead.
Library declarations
C++
void clear() noexcept;
Parameters
Parameter
Description
None
clear() takes no parameters. Call it with empty brackets.
Return Value
Return Value
Description
Nothing
clear() returns void. It is marked noexcept, so it does not throw.
The list of strings starts with "red" and "green".
clear() erases both strings. The list object words is still a valid list.
push_back("blue") adds one new node, so size() is 1 and front() is "blue".
Example 3 — begin() and end() After clear()
On an empty list, begin() and end() are equal. That is how a loop knows there is nothing to do.
C++
#include <iostream>
#include <list>
int main() {
std::list<int> l = {5, 6, 7};
l.clear();
std::cout << std::boolalpha;
std::cout << "begin == end: " << (l.begin() == l.end()) << '\n';
int sum = 0;
for (int n : l) {
sum += n;
}
std::cout << "loop ran, sum = " << sum << '\n';
return 0;
}
Output
begin == end: true
loop ran, sum = 0
How It Works
After clear() there is no first element, so begin() points to the same place as end().
The range-based for loop checks begin() != end() before each step. It is false at once, so the body never runs.
The sum stays at its starting value 0. Looping over an empty list is safe and does nothing.
Frequently Asked Questions
It erases all elements of the list. After the call, size() is 0 and empty() is true. The list object can be used again.
Yes. Each node of a list is its own allocation, so clear() destroys the elements and gives every node back to the allocator.
No. If you store raw pointers in the list, clear() only removes the pointers. You must delete the pointed-to objects yourself, or better, store smart pointers.
clear() always removes every element. erase() removes one element, or a range of elements, that you point to with iterators.
It takes time proportional to the number of elements, because each node must be destroyed one by one. After that, the list is empty.