简体   繁体   中英

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?

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 (ie 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.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM