C++ clear()
The clear() method is used to remove all elements from an std::unordered_set. After calling this method, the set will be empty, and its size will be zero.
The capacity of the set’s internal storage (the number of buckets) is typically not reduced by clear(). The container’s bucket structure is typically preserved, while memory used by individual elements is released.
All iterators, pointers, and references pointing to elements within the set are invalidated after calling clear().
Syntax
unordered_set_name.clear();
Parameters:
The method takes no parameters.
Return value:
The method returns void (nothing).
Example
This example uses clear() to remove all elements from an unordered_set and then verifies if its size is zero:
#include <iostream>#include <string>#include <unordered_set>int main() {std::unordered_set<std::string> planets = {"Mercury","Venus","Earth","Mars"};std::cout << "--- Before using clear() ---\n";std::cout << "Size: " << planets.size() << "\n";// Call clear() to remove all elementsplanets.clear();std::cout << "\n--- After using clear() ---\n";std::cout << "Size: " << planets.size() << "\n";if (planets.empty()) {std::cout << "The set is now empty.\n";}return 0;}
The output of this code is:
--- Before using clear() ---Size: 4--- After using clear() ---Size: 0The set is now empty.
Codebyte Example
In this example, clear() removes all elements from an unordered_set, after which a new element is inserted:
All contributors
- Anonymous contributor
Learn C++ on Codecademy
- Looking for an introduction to the theory behind programming? Master Python while learning data structures, algorithms, and more!
- Includes 6 Courses
- With Professional Certification
- Beginner Friendly.75 hours
- Learn C++ — a versatile programming language that’s important for developing software, games, databases, and more.
- Beginner Friendly.11 hours