C++ · Hash set · container
std::unordered_set<Key>
The standard hash set: average constant-time insert, membership and erase.
#include <unordered_set> template<class Key, class Hash = std::hash<Key>, class KeyEqual = std::equal_to<Key>, class Allocator = std::allocator<Key>> class unordered_set;
C++23 (contains and std::erase_if since C++20)
Operations
| Operation | Time | Worst case | Changes the collection |
|---|---|---|---|
| insert / emplace | O(1) | O(n) | Yes |
| contains / find / count | O(1) | O(n) | No |
| erase / std::erase_if | O(1) for erase(key) | O(n) for erase_if (visits every element) | Yes |
| insert(first, last): union | O(m) for m inserted elements | O(m · n) | Yes |
"Time" shows the amortized, expected or average bound when one applies; open an operation for the full profile and its assumptions.
How it works
- Representation
- The same node-based bucket structure as std::unordered_map, without mapped values.
- Ordering
- Unspecified; std::set keeps elements sorted.
- Duplicates
- Not stored (std::unordered_multiset allows them).
- Mutability
- Elements are const once inserted (changing one would break its hash); erase and re-insert instead.
- Memory and ownership
- One node per element; references survive rehashing.
- Equality and comparison
- Hash and KeyEqual, which must agree.
C# HashSet<T>, Python set and Java HashSet have set-algebra methods; std::unordered_set does not.
Pitfalls
- There are no union/intersection members, and std::set_union / std::set_intersection require sorted ranges, which an unordered_set is not. Insert ranges or loop with contains.
- Rehashing invalidates iterators.
- Custom types need a std::hash specialisation or a hasher parameter.
Alternatives
- std::set (sorted, O(log n), works with std::set_union)
- std::flat_set (C++23)
- std::bitset / std::vector<bool> for dense small integers
In other languages
- C#: HashSet<T>
- Python: set
- Java: HashSet<E>