c++unordered-maplinkedhashmap

equivalent LinkedHashmap in C++?


I have a Java program that I want to convert it to C++. So, there is a Linkedhashmap data structure used in the Java code and I want to convert it to C++. Is there an equivalent datatype for LinkedHashmap in C++?

I tried to use std::unordered_map, however, it does not maintain the order of the insertion.


Solution

  • C++ does not offer a collection template with the behavior that would mimic Java's LinkedHashMap<K,V>, so you would need to maintain the order separately from the mapping.

    This can be achieved by keeping the data in a std::list<std::pair<K,V>>, and keeping a separate std::unordered_map<K,std::list<std::pair<K,V>>::iterator> map for quick look-up of the item by key: