In C++, the std::unordered_set
is a container that provides unique elements in an unordered fashion. To manage performance effectively, it is often helpful to reserve capacity beforehand and shrink the capacity when it's no longer needed. This article demonstrates how to use the reserve
and shrink_to_fit
methods with std::unordered_set
.
#include <iostream>
#include <unordered_set>
int main() {
// Creating an unordered set
std::unordered_set my_set;
// Reserving capacity for 10 elements
my_set.reserve(10);
// Inserting elements
for (int i = 1; i <= 10; ++i) {
my_set.insert(i);
}
std::cout << "Size before shrink_to_fit: " << my_set.size() << std::endl;
// Shrinking to fit the current size
my_set.max_load_factor(1.0); // Reset load factor if needed
my_set.rehash(my_set.size()); // Rehashing to shrink
std::cout << "Size after shrink_to_fit: " << my_set.size() << std::endl;
return 0;
}
How do I avoid rehashing overhead with std::set in multithreaded code?
How do I find elements with custom comparators with std::set for embedded targets?
How do I erase elements while iterating with std::set for embedded targets?
How do I provide stable iteration order with std::unordered_map for large datasets?
How do I reserve capacity ahead of time with std::unordered_map for large datasets?
How do I erase elements while iterating with std::unordered_map in multithreaded code?
How do I provide stable iteration order with std::map for embedded targets?
How do I provide stable iteration order with std::map in multithreaded code?
How do I avoid rehashing overhead with std::map in performance-sensitive code?
How do I merge two containers efficiently with std::map for embedded targets?