C++ bucket_size()
The bucket_size() method returns the number of elements stored in a specific bucket of an unordered_set. An unordered_set stores elements in a hash table, where values are distributed into buckets based on their hash. This method helps inspect bucket distribution and understanding hash collisions.
Syntax
unordered_set_name.bucket_size(n)
Parameters:
n: The bucket number to query. This value must be less than the total number of buckets returned by bucket_count(). It is of type size_type, which is an unsigned integral type.
Return value:
The bucket_size() method returns the number of elements in bucket n as an unsigned integer of type size_type.
Example
This example shows how to inspect how elements are distributed across buckets in an unordered_set:
#include <iostream>#include <unordered_set>using namespace std;int main() {unordered_set<int> numbers = {10, 20, 30, 40, 50};size_t totalBuckets = numbers.bucket_count();cout << "Total buckets: " << totalBuckets << "\n";for (size_t i = 0; i < totalBuckets; i++) {cout << "Bucket " << i<< " has " << numbers.bucket_size(i)<< " elements\n";}return 0;}
This example results in the following output:
Total buckets: 5Bucket 0 has 5 elementsBucket 1 has 0 elementsBucket 2 has 0 elementsBucket 3 has 0 elementsBucket 4 has 0 elements
This output displays the number of elements assigned to each bucket. Some buckets may be empty, while others may contain multiple elements depending on the hash distribution.
Codebyte Example
This example demonstrates using bucket_size() to detect hash collisions by finding buckets that contain more than one element:
All contributors
- Anonymous contributor
Contribute to Docs
- Learn more about how to get involved.
- Edit this page on GitHub to fix an error or make an improvement.
- Submit feedback to let us know how we can improve Docs.
Learn C++ on Codecademy
- Looking for an introduction to the theory behind programming? Master Python while learning data structures, algorithms, and more!
- Includes 6 Courses
- With Professional Certification
- Beginner Friendly.75 hours
- Learn C++ — a versatile programming language that’s important for developing software, games, databases, and more.
- Beginner Friendly.11 hours