How do I provide stable iteration order with std::unordered_map in performance-sensitive code?

In performance-sensitive C++ code, when using std::unordered_map, it may be necessary to provide a stable iteration order. Since std::unordered_map does not guarantee any specific order of its elements, developers can implement a workaround by keeping a separate ordered container alongside the unordered map. Here’s an example of how you can achieve this.

#include <iostream> #include <unordered_map> #include <vector> #include <algorithm> int main() { std::unordered_map<:string int> unorderedMap; std::vector<:string> keys; // Inserting elements unorderedMap["apple"] = 1; unorderedMap["banana"] = 2; unorderedMap["orange"] = 3; // Collect keys to vector to maintain order for (const auto& pair : unorderedMap) { keys.push_back(pair.first); } // Sort the keys for stable iteration order std::sort(keys.begin(), keys.end()); // Iterating in stable order for (const std::string& key : keys) { std::cout << key << ": " << unorderedMap[key] << std::endl; } return 0; }

stable iteration std::unordered_map C++ performance-sensitive iteration order