In C++, std::unordered_map::bucket_size() tells you how many pairs live in one bucket.
If many keys hash to the same bucket, that bucket grows and lookups there get slower. Watching bucket sizes helps you understand collisions. 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
Pass a bucket index from 0 to bucket_count() - 1.
C++
std::size_t n = m.bucket_size(0); // how many pairs in bucket 0
for (std::size_t b = 0; b < m.bucket_count(); ++b) {
// m.bucket_size(b)
}
Call
What it does
m.bucket_size(n)
Returns the number of elements currently stored in bucket n.
The index n must be less than bucket_count(). Passing an out-of-range index is undefined behavior.
Library declarations
C++
size_type bucket_size(size_type n) const;
Parameters
Parameter
Description
n
Bucket index in the range [0, bucket_count()).
Return Value
Return Value
Description
size_type
How many elements are in that bucket. 0 means empty.
C++ Examples
Example 1 — Check Bucket 0
Print the size of bucket 0 after inserting a few keys.