Hash Sets using std::unordered_set

Difference between rehash() and reserve()

What is the difference between rehash() and reserve() in std::unordered_set?

Abstract art representing computer programming

Both rehash() and reserve() can be used to optimize the performance of a std::unordered_set by preallocating buckets. However, they differ in how they determine the number of buckets to allocate.

  • rehash(n) explicitly sets the number of buckets to at least n.
  • reserve(n) sets the number of buckets based on the container's max_load_factor() and the expected number of elements n.

Here's an example to illustrate the difference:

#include <iostream>
#include <unordered_set>

int main() {
  std::unordered_set<int> Set;


  std::cout << "After rehash(100):\n";
  std::cout << "Bucket count: "
    << Set.bucket_count() << "\n";  

  std::cout << "After reserve(100):\n";
  std::cout << "Bucket count: "
    << Set.bucket_count() << "\n";  
After rehash(100):
Bucket count: 128
After reserve(100):
Bucket count: 256

In this example:

  • We set the max_load_factor() to 0.5
  • Calling rehash(100) directly sets the number of buckets to at least 100. The actual number of buckets may be higher to satisfy the container's requirements. In this case, it created 128 buckets.
  • Calling reserve(100) calculates the number of buckets based on the expected number of elements (100) and the max_load_factor() (0.5). In this case, it elects to create 256 buckets to accommodate 100 elements with a load factor of 0.5.

The key difference is that rehash() explicitly sets the minimum number of buckets, while reserve() calculates the number of buckets based on the expected number of elements and the max_load_factor().

It's generally recommended to use reserve() when you have an estimate of the final size of the container, as it takes into account the load factor. Use rehash() when you need explicit control over the number of buckets.

Answers to questions are automatically generated and may not have been reviewed.

Free, Unlimited Access

Professional C++

Comprehensive course covering advanced concepts, and how to use them on large-scale projects.

Screenshot from Warhammer: Total War
Screenshot from Tomb Raider
Screenshot from Jedi: Fallen Order
Contact|Privacy Policy|Terms of Use
Copyright © 2024 - All Rights Reserved