In C++, std::unordered_set::clear()removes all values from the unordered_set. After the call, size() is 0 and empty() is true.
The unordered_set object itself stays alive and works as before, so you can insert new values at once. Every iterator and reference to the old values becomes invalid. Include <unordered_set> to use it.
This is a member of std::unordered_set<T>, a hash table of unique values. Find, insert, and erase are usually average constant time. Unlike std::set, values are not sorted and iteration order is unspecified. Elements are const, so you cannot change a stored value through an iterator. There is no operator[] and no at(). Prefer find() or contains() to look up a value, and call reserve() before many inserts.
Syntax
Call it with empty brackets. It removes everything.
C++
std::unordered_set<int> s = {1, 2, 3};
s.clear();
// s.size() is 0
// s.empty() is true
Call
What it does
s.clear()
Removes all values. The call returns nothing.
clear() works in linear time, because each value must be destroyed. To remove only some values, use erase(). An unordered_set has no capacity(), so there is no extra reserved memory to worry about after clear().
Library declarations
C++
void clear() noexcept;
Parameters
Parameter
Description
None
clear() takes no parameters. Call it with empty brackets.
Return Value
Return Value
Description
void
Nothing is returned. The unordered_set is empty after the call.
C++ Examples
Example 1 — clear() Removes Everything
Fill an unordered_set with three numbers, clear it, and check the size.
The unordered_set starts with three values, so the first line prints 3.
s.clear() destroys every value in one call. There is no loop and no argument.
The size is now 0 and empty() returns true. The unordered_set is a normal empty unordered_set, ready for new values.
Example 2 — clear() to Reuse a Set
Count the different values in each batch with a single set that is cleared between batches.
C++
#include <iostream>
#include <unordered_set>
#include <vector>
int main() {
std::vector<std::vector<int>> batches = {{1, 1, 2}, {5, 6, 7, 5}};
std::unordered_set<int> seen;
for (std::size_t i = 0; i < batches.size(); ++i) {
for (int v : batches[i]) {
seen.insert(v);
}
std::cout << "batch " << i + 1 << ": " << seen.size() << " unique\n";
seen.clear();
}
return 0;
}
Output
batch 1: 2 unique
batch 2: 3 unique
How It Works
There are two batches of numbers. One set called seen is used for both of them.
Batch 1 is 1, 1, 2. The unordered_set drops the repeat, so it holds 1 and 2 and reports 2 unique values.
seen.clear() empties the unordered_set before batch 2. If it was skipped, the old values would stay and the second count would be wrong. Batch 2 is 5, 6, 7, 5, which gives 3 unique values.
Example 3 — clear() Only Affects One Set
Copy an unordered_set, clear the original, and see that the copy keeps its values.