CodexBloom - Programming Q&A Platform

std::unordered_map not preserving insertion order when using custom hash function in C++20

πŸ‘€ Views: 54 πŸ’¬ Answers: 1 πŸ“… Created: 2025-06-14
c++ unordered-map hash-function data-structures C++

I'm facing an issue with `std::unordered_map` where I expected the elements to maintain a certain order based on their insertion, but that doesn't seem to be happening when I use a custom hash function. I have implemented a simple object as a key that holds two strings, and my hash function combines their hashes. Here’s the relevant code: ```cpp #include <iostream> #include <unordered_map> #include <string> struct MyKey { std::string first; std::string second; bool operator==(const MyKey& other) const { return first == other.first && second == other.second; } }; struct MyHash { std::size_t operator()(const MyKey& key) const { return std::hash<std::string>()(key.first) ^ std::hash<std::string>()(key.second); } }; int main() { std::unordered_map<MyKey, int, MyHash> myMap; myMap[{"apple", "red"}] = 1; myMap[{"banana", "yellow"}] = 2; myMap[{"cherry", "dark red"}] = 3; for (const auto& pair : myMap) { std::cout << pair.first.first << ", " << pair.first.second << " -> " << pair.second << '\n'; } return 0; } ``` When I run this code, the output is not in the order I inserted the elements. The expected output should be: ``` apple, red -> 1 banana, yellow -> 2 cherry, dark red -> 3 ``` However, the actual output seems to be arbitrary due to how `std::unordered_map` organizes its elements. I've read that `std::unordered_map` does not guarantee order, which makes sense, but I need to maintain the insertion order. I attempted to use `std::vector` alongside `std::unordered_map`, storing the insertion order in the vector and using the map for quick lookups, but that seems cumbersome and defeats the purpose of using a map. Is there a way to achieve ordered insertion while still using a hash map? Should I be looking into `std::unordered_map` alternatives or perhaps combining data structures in a more efficient manner?