Last Updated : 28 Jun, 2022
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 program to illustrate the
// unordered_set::bucket_size() function
#include <iostream>
#include <unordered_set>
using namespace std;
int main()
{
unordered_set<int> sampleSet;
// to store number of buckets
int bucketCount;
// Inserting elements
sampleSet.insert(5);
sampleSet.insert(10);
sampleSet.insert(15);
sampleSet.insert(20);
sampleSet.insert(25);
bucketCount = sampleSet.bucket_count();
// displaying number of buckets
cout << "sampleSet has " << bucketCount << " buckets\n";
// displaying number of elements in bucket numbered 1
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
// CPP program to illustrate the
// unordered_set::bucket_size() function
#include <iostream>
#include <unordered_set>
using namespace std;
int main()
{
unordered_set<string> sampleSet;
// to store number of buckets
int bucketCount;
// Inserting elements
sampleSet.insert("Welcome");
sampleSet.insert("To");
sampleSet.insert("GeeksforGeeks");
sampleSet.insert("Computer Science Portal");
sampleSet.insert("For Geeks");
bucketCount = sampleSet.bucket_count();
// displaying number of buckets
cout << "sampleSet has " << bucketCount << " buckets\n";
// displaying number of elements in bucket numbered 0
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)
RetroSearch is an open source project built by @garambo | Open a GitHub Issue
Search and Browse the WWW like it's 1997 | Search results from DuckDuckGo
HTML:
3.2
| Encoding:
UTF-8
| Version:
0.7.4