bucket_count and bucket_size in unordered_map in C++
Unordered_map is an associated container that stores elements formed by the combination of key-value and a mapped value. The key value is used to uniquely identify the element and the mapped value is the content associated with the key. Both key and value can be of any type predefined or user-defined.
Bucket: Internally, unordered_map is implemented using a hash table so, a bucket is a slot in the internal hash Table to which elements are assigned based on the hash value of their key. Buckets are numbered from 0 to (bucket_count-1). Hence this function returns the bucket no. where the element with key is located in unordered_map.
Time Complexity: O(1).
unordered_map.bucket(k); // k is the key corresponds to which // we want to know bucket number.
Return Value: The order number of the bucket corresponding to key k.
There are two more functions regarding bucket:
1. std::bucket_count: This function is used to count the total no. of buckets in the unordered_map. No parameter is required to pass into this function.
Time Complexity: O(1).
Return Value: The number of the bucket present in the hash table of unordered_map.
2. std::bucket_size: This function count the number of elements present in each bucket of the unordered_map.
Time Complexity: Linear in the bucket size.
unordered_map.bucket_size(i); // 'i' is the bucket number in which we want // to find no. of elements. (i < bucket_count)
Return Value: The number of elements present in bucket ‘i’.
(loge, 1) is in bucket= 5 (e, 2.718) is in bucket= 4 (log10, 2.302) is in bucket= 4 (PI, 3.14) is in bucket= 0 (root2, 1.414) is in bucket= 3 umap has 7 buckets. Bucket 0 has 1 elements. Bucket 1 has 0 elements. Bucket 2 has 0 elements. Bucket 3 has 1 elements. Bucket 4 has 2 elements. Bucket 5 has 1 elements. Bucket 6 has 0 elements.
We can also print all the elements present in each bucket of the unordered_map.
Bucket 0 contains: (PI, 3.14) Bucket 1 contains: Bucket 2 contains: Bucket 3 contains: (root2, 1.414) Bucket 4 contains: (e, 2.718) (log10, 2.302) Bucket 5 contains: (loge, 1) Bucket 6 contains:
Use of bucket in std::unordered_map: There is a number of algorithms that require the objects to be hashed into some number of buckets, and then each bucket is processed. Let say, you want to find duplicates in a collection. You hash all items in the collection, then in each bucket, you compare items pairwise. A bit less trivial example is the Apriori algorithm for finding frequent itemsets.
This article is contributed by Akash Gupta. If you like GeeksforGeeks and would like to contribute, you can also write an article using write.geeksforgeeks.org or mail your article to firstname.lastname@example.org. See your article appearing on the GeeksforGeeks main page and help other Geeks. Please write comments if you find anything incorrect, or you want to share more information about the topic discussed above.