What's the difference between the rehash()
and reserve()
methods of the C++ unordered_map
? Why are two different methods needed?
The difference is in purpose, although both are doing something similar.
rehash
takes an existing map and rebuilds a new size of buckets, rehashing in the process and redistributing elements into the new buckets.
reserve
guarantees you that if you don't insert more than the reserved number of elements, there will be no rehashing (i.e. your iterators will remain valid).
Those are two somewhat different things, albeit related. rehash
doesn't give you any guarantees, and reserve
doesn't express the purpose of rehashing. Use rehash
if you think your map is inefficient, and reserve
if you're preparing for a lot of insertions.
As @Xeo points out, reserve
is just a wrapper around rehash
, though, taking into account the permissible load factor of the map.
From cplusplus.com:
rehash: A rehash is the reconstruction of the hash table: All the elements in the > container are rearranged according to their hash value into the new set of buckets. This > may alter the order of the elements within the container.
reserve: Sets the number of buckets in the container (bucket_count) to the most appropriate > to contain at least n elements.
I understand from here that rehash tries to change number of buckets in hashtable in respect to given size of n. reserve changes number of buckets in hashtable to the most appropriate number in order to store at least n (given by user) elements. I hope i made my statement clear.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With