ARTICLE AD BOX
I'm experimenting with std::unordered_map performance in C++20 and noticed that when I insert a large number of elements, the container sometimes rehashes multiple times even though I called reserve() beforehand.
Example code:
#include <unordered_map> #include <string> int main() { std::unordered_map<int, std::string> m; m.reserve(100000); for (int i = 0; i < 100000; i++) { m[i] = "value"; } }My Questions:
Why does reserve() not completely prevent rehashing in all cases? Does the rehash behavior depend on implementation details of libstdc++/libc++? Is there a portable way to control bucket count or avoid rehashing entirely? Would using rehash() be more appropriate?I've read the cppreference entry on unordered_map but still don't fully understand the exact rules for when rehashing happens. Any insight is appreciated!
