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;
Set.max_load_factor(0.5);
Set.rehash(100);
std::cout << "After rehash(100):\n";
std::cout << "Bucket count: "
<< Set.bucket_count() << "\n";
Set.reserve(100);
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:
max_load_factor()
to 0.5rehash(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.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.
std::unordered_set
This lesson provides a thorough understanding of std::unordered_set
, from basic initialization to handling custom types and collisions