What is the difference between rehash () and reserve () methods for C ++ unordered_map?

What is the difference between rehash() and reserve() methods for C ++ unordered_map ? Why are two different methods needed?

+4
source share
2 answers

The difference in purpose, although both do something similar.

  • rehash takes an existing map and rebuilds the new bucket size, rewrites the process and redistributes the elements into new buckets.

  • reserve guarantees you that if you do not enter more than the reserved number of elements, there will be no re-writing (i.e. your iterators will remain valid).

These are two different things, though related. rehash does not give you any guarantees, and reserve does not express the purpose of re-recording. Use rehash if you think your card is ineffective, and reserve if you are preparing for a lot of inserts.

As @Xeo points out, reserve is just a wrapper around rehash , although given the allowable load factor on the map.

+7
source

From cplusplus.com :

rehash: rework is restoring a hash table: all items in the container> are regrouped according to their hash value into a new bucket set. This> can reorder items in the container.

reserve: Sets the number of buckets in the container (bucket_count) for the most suitable> to contain at least n elements.

I understand from here that rehash is trying to change the number of buckets in the hash table in relation to a given size n. reserves changes in the number of buckets in the hash table for the most suitable number in order to store at least n (user-defined) elements. I hope I made my expression clear.

0
source

All Articles