What is the unordered_map::bucket() function in C++?

In this shot, we will learn how to use the unordered_map::bucket() function in C++. It is available in the <unordered_map> header file in C++.

The unordered_map::bucket() function is used to obtain the bucket number of a specified key.

When elements are added to the hash map, a hash value is calculated for the key that needs to be inserted. This hash value corresponds to a bucket, which is a slot in the internal memory that links all the keys associated with that hash value.

Syntax

The syntax of the unordered_map::bucket() function is given below:

size_type bucket(K key);

Parameter

The unordered_map::bucket() method accepts the parameters mentioned below:

  • Key: The key whose bucket number needs to be determined.

Return

unordered_map::bucket() returns the bucket number of specified key.

Code

Let’s have a look at the code now.

#include <iostream>
#include <unordered_map>
using namespace std;
int main()
{
unordered_map<int,string> umap ={
{12, "unordered"},
{16, "map"},
{89, "in"},
{66, "C++"}
};
cout<<"The bucket number of key = 89 is: " << umap.bucket(89);
return 0;
}

Explanation

  • In lines 1 and 2, we imported the required header files.
  • In line 5, we made a main() function.
  • From lines 7 to 12, we initialized an unordered map with integer type keys and string type values.
  • In line 14, we used the unordered_map::bucket() function to get the bucket number of the specified key and displayed it.

So, this is how to use the unordered_map::bucket() function in C++ to get the bucket number for a key.

Free Resources