Related Articles

Related Articles

unordered_set bucket_size() in C++ STL
  • Difficulty Level : Basic
  • Last Updated : 28 Oct, 2020

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

filter_none

edit
close

play_arrow

link
brightness_4
code

// 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;
}

chevron_right


Output

sampleSet has 7 buckets
Bucket number 3 contains 1 elements

Program 2

CPP

filter_none

edit
close

play_arrow

link
brightness_4
code

// 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;
}

chevron_right


Output

sampleSet has 7 buckets
Bucket number 0 contains 0 elements 

Rated as one of the most sought after skills in the industry, own the basics of coding with our C++ STL Course and master the very concepts by intense problem-solving.




My Personal Notes arrow_drop_up
Recommended Articles
Page :