C++ unordered_multimap - bucket_count() Function
The C++ unordered_multimap::bucket_count function returns the number of buckets in the unordered_multimap.
As an unordered_multimap is implemented using hash table where a bucket is a slot in the container's internal hash table to which elements are assigned based on the hash value of their key. The number of buckets directly influences the load_factor of the container's hash table. The container automatically increases the number of buckets to keep the load_factor below its max_load_factor which causes rehash whenever the number of buckets is increased.
Syntax
size_type bucket_count() const noexcept;
Parameters
No parameter is required.
Return Value
Number of buckets in the unordered_multimap.
Time Complexity
Constant i.e, Θ(1).
Example:
In the example below, the unordered_multimap::bucket_count function returns the number of buckets in uMMap.
#include <iostream> #include <unordered_map> using namespace std; int main (){ unordered_multimap<string, string> uMMap; uMMap = {{"CAN", "Ottawa"}, {"USA", "Washington"}, {"IND", "Delhi"}, {"CAN", "Toronto"}}; cout<<"uMMap contains "<<uMMap.bucket_count()<<" buckets:"; for(unsigned int i = 0; i < uMMap.bucket_count(); i++) { cout<<"\nThe bucket #"<<i<<" contains: "; for(auto it = uMMap.begin(i); it != uMMap.end(i); ++it) { cout<<it->first<<":"<<it->second<<" "; } } return 0; }
The output of the above code will be:
uMMap contains 13 buckets: The bucket #0 contains: The bucket #1 contains: The bucket #2 contains: The bucket #3 contains: The bucket #4 contains: The bucket #5 contains: The bucket #6 contains: The bucket #7 contains: The bucket #8 contains: The bucket #9 contains: The bucket #10 contains: USA:Washington The bucket #11 contains: IND:Delhi The bucket #12 contains: CAN:Toronto CAN:Ottawa
❮ C++ <unordered_map> Library