How do I reserve and rehash properly with std::unordered_map?

In C++, when using `std::unordered_map`, it's important to manage memory effectively, especially when it comes to reserving space and rehashing. Reserving space before inserting elements can improve performance by reducing the need to resize the hash table. Here's how you can do it properly.

C++, unordered_map, reserve, rehash, performance optimization

This guide discusses how to efficiently use std::unordered_map in C++ by understanding the importance of reserving space and rehashing for optimal performance.

#include <iostream>
#include <unordered_map>

int main() {
    // Create an unordered_map
    std::unordered_map umap;

    // Reserve space for 100 elements to optimize performance
    umap.reserve(100);

    // Inserting elements
    for (int i = 0; i < 100; ++i) {
        umap[i] = "Value " + std::to_string(i);
    }

    // Check the current load factor
    std::cout << "Load factor: " << umap.load_factor() << std::endl;

    // Rehash to increase the number of buckets to 200
    umap.rehash(200);

    // Output the number of buckets
    std::cout << "Number of buckets after rehash: " << umap.bucket_count() << std::endl;

    return 0;
}
        

C++ unordered_map reserve rehash performance optimization