Short answer
C does not have a built-in hash set. The C standard library has no hash table or set type. In C++, the standard tool for this job is std::unordered_set, which is declared in the <unordered_set> header. It stores unique elements, finds them with a hash function, and does not keep them in any particular order.
This guide covers how to create one, check and remove elements, loop over them, use your own types, and avoid common mistakes.
What a hash set does
A hash set holds a group of unique values. You can add a value, check whether a value is present, and remove a value. On average, these operations take constant time, which means the time does not grow with the number of items. In the worst case they take time proportional to the number of items, but a good hash function makes that rare.
A hash set does not keep its items in order. You also cannot ask for “the third item” the way you can with a std::vector.
Creating and filling a std::unordered_set
Include the header and give the element type in angle brackets. This example uses std::string:
#include <iostream>
#include <string>
#include <unordered_set>
int main() {
std::unordered_set<std::string> fruits = {"apple", "banana"};
fruits.insert("cherry");
fruits.insert("apple"); // already present, so nothing changes
std::cout << "Size: " << fruits.size() << "\n"; // prints 3
return 0;
}
insert() adds an element. If the element is already in the set, nothing changes. insert() returns a std::pair. Its second member is true when the element was added and false when it was already there:
auto result = fruits.insert("apple");
if (!result.second) {
std::cout << "apple was already in the set\n";
}
Checking, counting and removing elements
To check whether an element is present, use find() and compare the result with end():
if (fruits.find("banana") != fruits.end()) {
std::cout << "banana is in the set\n";
}
find() returns an iterator. If the element is missing, it returns fruits.end().
count() returns how many matching elements exist. In an unordered set that is always 0 or 1:
std::cout << fruits.count("cherry") << "\n"; // prints 1
Since C++20, contains() returns a bool directly, which reads more clearly:
if (fruits.contains("banana")) {
std::cout << "banana is in the set\n";
}
To remove an element, pass its value to erase():
fruits.erase("banana");
If you compile with a standard earlier than C++20, use find() or count() instead of contains().
Looping over the elements
A range-based for loop visits every element:
for (const std::string& fruit : fruits) {
std::cout << fruit << "\n";
}
The order of the output is not defined. It may not match the order you inserted the values, and it can change after more inserts, because the set may rehash to make room. Write code that does not depend on the order. If you need the items sorted, copy them into a std::vector and sort that.
Using your own type
A hash set needs two things for each element type: a way to compute a hash value, and a way to test two elements for equality with ==. The standard library supplies both for common types such as int and std::string. For your own struct, you provide them:
#include <cstddef>
#include <functional>
#include <iostream>
#include <unordered_set>
struct Point {
int x;
int y;
bool operator==(const Point& other) const {
return x == other.x && y == other.y;
}
};
struct PointHash {
std::size_t operator()(const Point& p) const {
return std::hash<int>()(p.x) ^ (std::hash<int>()(p.y) << 1);
}
};
int main() {
std::unordered_set<Point, PointHash> points;
points.insert(Point{1, 2});
points.insert(Point{1, 2}); // duplicate, so nothing is added
std::cout << points.size() << "\n"; // prints 1
return 0;
}
PointHash combines the hashes of the two coordinates. This is a simple way to combine them, used here for illustration. The one rule your hash must follow is that equal points produce equal hash values. A weak hash still works, but it slows the set down because many points share a bucket.
When to choose a hash set
A hash set is a good fit when you:
- need to check quickly whether an item is present
- want to remove duplicates from a collection
- do not need the items in any particular order
If you need the items sorted, the guide on sets in c explains std::set. It is usually built on a balanced tree, so its operations take time that grows with the logarithm of the number of elements.
If each key needs a value attached to it, you want a map instead. In C++ that is std::unordered_map, and the guide on dictionary in c covers the key-value pattern.
Common mistakes
- Assuming an order. Iteration order is not defined, so do not rely on it.
- Expecting duplicates. A
std::unordered_setstores each value once. If you need repeats, usestd::unordered_multiset. - Keeping iterators across inserts. An insert can trigger a rehash, which invalidates iterators. Look the element up again instead of holding on to an old iterator.
- Using a type with no hash or equality test. A struct with no hash and no
==will not compile in astd::unordered_set.
Summary
A hash set in C++ is std::unordered_set. It stores unique values, checks membership quickly on average, and keeps no order. Use insert() to add, find(), count() or contains() to check, and erase() to remove. For your own types, provide a hash function and ==.