unordered_set bucket_size() in C++ STL

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:

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;
  
    // Inserting elements
    sampleSet.insert(5);
    sampleSet.insert(10);
    sampleSet.insert(15);
    sampleSet.insert(20);
    sampleSet.insert(25);
  
    // displaying number of elements in bucket numbered 1
    cout << "Bucket number 3 contains " << sampleSet.bucket_size(3)
         << " elements";
  
    return 0;
}

chevron_right


Output:

Bucket number 3 contains 1 elements

Program 2:

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;
  
    // Inserting elements
    sampleSet.insert("Welcome");
    sampleSet.insert("To");
    sampleSet.insert("GeeksforGeeks");
    sampleSet.insert("Computer Science Portal");
    sampleSet.insert("For Geeks");
  
    // displaying number of elements in bucket numbered 0
    cout << "Bucket number 0 contains " << sampleSet.bucket_size(0)
         << " elements";
  
    return 0;
}

chevron_right


Output:

Bucket number 3 contains 1 elements


My Personal Notes arrow_drop_up

Check out this Author's contributed articles.

If you like GeeksforGeeks and would like to contribute, you can also write an article using contribute.geeksforgeeks.org or mail your article to contribute@geeksforgeeks.org. See your article appearing on the GeeksforGeeks main page and help other Geeks.

Please Improve this article if you find anything incorrect by clicking on the "Improve Article" button below.