The unordered_set::bucket_size() function is a built-in function in C++ STL which returns the total number of elements present in a specific bucket in an unordered_set container.
The bucket is a slot in the unordered_set’s internal hash table where elements are stored.
Note: Buckets in unordered_set are numbered from 0 to n-1, where n is the total number of buckets.
Syntax:
unordered_set.bucket_size(n);
Parameter: This function accepts a single parameter n which is mandatory. This parameter represents the bucket number for which it is needed to find the total number of elements.
Return Value: This function returns the total number of elements present in the bucket n.
Below programs illustrate the unordered_set::bucket_size() function:
Program 1:
CPP
#include <iostream>
#include <unordered_set>
using namespace std;
int main()
{
unordered_set< int > sampleSet;
int bucketCount;
sampleSet.insert(5);
sampleSet.insert(10);
sampleSet.insert(15);
sampleSet.insert(20);
sampleSet.insert(25);
bucketCount = sampleSet.bucket_count();
cout << "sampleSet has " << bucketCount << " buckets\n" ;
cout << "Bucket number 3 contains "
<< sampleSet.bucket_size(3) << " elements" ;
return 0;
}
|
Output:
sampleSet has 7 buckets
Bucket number 3 contains 1 elements
Program 2:
CPP
#include <iostream>
#include <unordered_set>
using namespace std;
int main()
{
unordered_set<string> sampleSet;
int bucketCount;
sampleSet.insert( "Welcome" );
sampleSet.insert( "To" );
sampleSet.insert( "GeeksforGeeks" );
sampleSet.insert( "Computer Science Portal" );
sampleSet.insert( "For Geeks" );
bucketCount = sampleSet.bucket_count();
cout << "sampleSet has " << bucketCount << " buckets\n" ;
cout << "Bucket number 0 contains "
<< sampleSet.bucket_size(0) << " elements" ;
return 0;
}
|
Output:
sampleSet has 7 buckets
Bucket number 0 contains 0 elements
Time complexity: O(N)