Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

What's the difference between the rehash() and reserve() methods of the C++ unordered_map?

What's the difference between the rehash() and reserve() methods of the C++ unordered_map? Why are two different methods needed?

like image 615
static_rtti Avatar asked Feb 13 '13 10:02

static_rtti


2 Answers

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.

like image 68
Kerrek SB Avatar answered Sep 30 '22 12:09

Kerrek SB


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.

like image 24
haitaka Avatar answered Sep 30 '22 14:09

haitaka