Skip to content
Related Articles

Related Articles

unordered_multimap bucket() function in C++ STL
  • Last Updated : 08 Aug, 2018

The unordered_multimap::bucket() is a built-in function in C++ STL which returns the bucket number in which a given key is. Bucket size varies from 0 to bucket_count-1.

Syntax:

unordered_multimap_name.bucket(key)

Parameters: The function accepts a single mandatory parameter key which specifies the key whose bucket number is to be returned.

Return Value: It returns an unsigned integral type which signifies the bucket number in which the key is.

Below programs illustrates the above function:



Program 1:




// C++ program to illustrate the
// unordered_multimap::bucket() 
#include <bits/stdc++.h>
using namespace std;
  
int main()
{
  
    // declaration
    unordered_multimap<int, int> sample;
  
    // inserts key and element
    sample.insert({ 10, 100 });
    sample.insert({ 10, 100 });
    sample.insert({ 20, 200 });
    sample.insert({ 30, 300 });
    sample.insert({ 15, 150 });
  
    // iterate for all elements and print its bucket number
    for (auto it = sample.begin(); 
                  it != sample.end(); it++) {
        cout << "The bucket number in which {" 
             << it->first << ", " 
             << it->second << "} is " 
             << sample.bucket(it->first) << endl;
    }
    return 0;
}
Output:
The bucket number in which {15, 150} is 1
The bucket number in which {30, 300} is 2
The bucket number in which {20, 200} is 6
The bucket number in which {10, 100} is 3
The bucket number in which {10, 100} is 3

Program 2:




// C++ program to illustrate the
// unordered_multimap::bucket() 
#include <bits/stdc++.h>
using namespace std;
  
int main()
{
  
    // declaration
    unordered_multimap<char, char> sample;
  
    // inserts key and element
    sample.insert({ 'a', 'b' });
    sample.insert({ 'a', 'b' });
    sample.insert({ 'b', 'c' });
    sample.insert({ 'r', 'a' });
    sample.insert({ 'c', 'b' });
  
    // iterate for all elements and print its bucket number
    for (auto it = sample.begin(); 
                    it != sample.end(); it++) {
        cout << "The bucket number in which {" 
             << it->first << ", "
             << it->second << "} is " 
             << sample.bucket(it->first) << endl;
    }
    return 0;
}
Output:
The bucket number in which {c, b} is 1
The bucket number in which {r, a} is 2
The bucket number in which {b, c} is 0
The bucket number in which {a, b} is 6
The bucket number in which {a, b} is 6
Want to learn from the best curated videos and practice problems, check out the C++ Foundation Course for Basic to Advanced C++ and C++ STL Course for foundation plus STL.  To complete your preparation from learning a language to DS Algo and many more,  please refer Complete Interview Preparation Course.
My Personal Notes arrow_drop_up
Recommended Articles
Page :