In C++, std::set::clear()removes all values from the set. After the call, size() is 0 and empty() is true.
The 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 <set> to use it.
This is a member of std::set<T>, a sorted container of unique values. A set never keeps a duplicate and always holds its values in sorted order, so it can find, insert, and erase a value in logarithmic time. A set has no operator[] and no at(), because the value is its own key. Every element is const, so you cannot change a value through an iterator.
Syntax
Call it with empty brackets. It removes everything.
C++
std::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(). A 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 set is empty after the call.
C++ Examples
Example 1 — clear() Removes Everything
Fill a set with three numbers, clear it, and check the size.
The 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 set is a normal empty 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 <set>
#include <vector>
int main() {
std::vector<std::vector<int>> batches = {{1, 1, 2}, {5, 6, 7, 5}};
std::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 set drops the repeat, so it holds 1 and 2 and reports 2 unique values.
seen.clear() empties the 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 a set, clear the original, and see that the copy keeps its values.