In C++, std::unordered_set::bucket_size() tells you how many values 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_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
Pass a bucket index from 0 to bucket_count() - 1.
C++
std::size_t n = m.bucket_size(0); // how many values 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.