In C++, std::unordered_set::bucket_count() returns how many buckets the hash table has right now.
Think of buckets as a row of boxes. A hash function turns each value into a number, and that number picks a box. Several values can share a box; that is called a collision. 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 bucket_count with empty brackets.
C++
std::size_t n = m.bucket_count(); // current number of buckets
std::cout << n;
Call
What it does
m.bucket_count()
Returns the current number of buckets as size_type.
The count can grow when you insert many values, or when you call rehash() / reserve(). An empty unordered_set may still have some buckets ready.
Library declarations
C++
size_type bucket_count() const;
Parameters
Parameter
Description
None
bucket_count() takes no parameters. Call it with empty brackets.
Return Value
Return Value
Description
size_type
The number of buckets in the hash table right now.
C++ Examples
Example 1 — bucket_count() After Creating a Set
Print size and bucket_count for a small unordered_set.
bucket_count() > 0 is true, so the table has a real bucket array. Exact counts differ by library, so the demo prints booleans.
The last check shows there are at least as many buckets as keys in this small example.
Example 2 — Bucket Count After Many Inserts
Insert many keys and show that the bucket count can rise.
C++
#include <iostream>
#include <unordered_set>
int main() {
std::unordered_set<int> m;
std::size_t before = m.bucket_count();
for (int i = 0; i < 100; ++i) {
m.insert(i);
}
std::cout << "before inserts: " << before << '\n';
std::cout << "after inserts: " << m.bucket_count() << '\n';
std::cout << "size: " << m.size() << '\n';
return 0;
}
Output
before inserts: 1
after inserts: 103
size: 100
How It Works
A new unordered_set starts with a small table. before stores that early bucket count.
One hundred inserts may force the table to grow so the load factor stays under the maximum.
After the loop, size() is 100 and bucket_count() is larger than at the start. Exact numbers can vary by library; the value idea is that the table can expand.
Example 3 — bucket_count() Versus size()
Clear the unordered_set and show that buckets can remain while size is zero.