How do I reserve capacity and shrink-to-fit with std::unordered_map?

In C++, the `std::unordered_map` is a powerful data structure that allows for efficient storage and retrieval of key-value pairs. To optimize performance, developers can reserve capacity for the unordered map and also shrink its capacity to match its size when necessary.

Reserving Capacity

To reserve a certain capacity for an `std::unordered_map`, you can use the `reserve()` member function. This can help avoid multiple reallocations as you insert elements into the map.

Shrink-to-Fit

If you want to reduce the memory usage of an `std::unordered_map`, you can utilize the `shrink_to_fit()` member function. This initializes the size of the container to its current number of elements, thus potentially freeing unused memory.

Example

#include <iostream> #include <unordered_map> int main() { std::unordered_map myMap; // Reserve capacity myMap.reserve(100); std::cout << "Reserved capacity for 100 elements." << std::endl; // Inserting elements for (int i = 0; i < 100; ++i) { myMap[i] = "Value " + std::to_string(i); } // Check the size and capacity std::cout << "Current size: " << myMap.size() << std::endl; // Shrink to fit myMap.shrink_to_fit(); std::cout << "Shrink to fit called." << std::endl; return 0; }

std::unordered_map reserve capacity shrink-to-fit C++ data structures memory management optimizing performance