Reputation: 1584
std::unordered_map
and std::vector
both have the reserve
method, which increases the capacity of the collection so that it would be possible to add multiple elements to the collection without enlarging the internal buffer. However, std::vector
also has a method capacity()
that returns the current capacity of the collection. std::unordered_map
does not have such a method. Is there any way to obtain the capacity of std::unordered_map
using whatever the class already provides?
Upvotes: 6
Views: 2655
Reputation: 3265
The docs of std::unordered_map::reserve state
void reserve ( size_type n );
Request a capacity change
Sets the number of buckets in the container (bucket_count) to the most appropriate to contain at least n elements.
If n is greater than the current bucket_count multiplied by the max_load_factor, the container's bucket_count is increased and a rehash is forced.
If n is lower than that, the function may have no effect.
So the equivalent to std::vector::capacity, where reserve changes the capacity when new_cap
is greater than capacity()
would be:
std::unordered_map::bucket_count() * std::unordered_map::max_load_factor
Upvotes: 0
Reputation: 11370
A map contains a number of buckets (see bucket_count()
) and each bucket can contain a certain number of elements (see max_load_factor()
). So the total capactity of a std::unordered_map<X, Y> m;
is
m.max_load_factor() * m.bucket_count();
Upvotes: 2
Reputation: 39085
size_type std::unordered_map::bucket_count()
std::unordered_map::reserve(size_type n)
requests a capacity change.
Sets the number of buckets in the container (bucket_count
) to the most appropriate to contain at least n
elements.
Upvotes: 0