In C++, std::unordered_map::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 key into a number, and that number picks a box. Several keys can share a box; that is called a collision. Include <unordered_map> to use it.
This is a member of std::unordered_map<Key, T>, a hash table of key and value pairs. Each key is unique. Find, insert, and erase are usually average constant time. Unlike std::map, keys are not sorted and iteration order is unspecified. Read a value with at() or find(). The m[key] operator also works, but it adds a default value when the key is missing.
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 keys, or when you call rehash() / reserve(). An empty unordered_map 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 Map
Print size and bucket_count for a small unordered_map.
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_map>
int main() {
std::unordered_map<int, int> m;
std::size_t before = m.bucket_count();
for (int i = 0; i < 100; ++i) {
m[i] = i * 10;
}
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_map 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 key idea is that the table can expand.
Example 3 — bucket_count() Versus size()
Clear the map and show that buckets can remain while size is zero.