My goal is to write a class that works like a unordered_map but keeps the insertion order of the elements while still allowing O(1) lookup by key.
My approach is as follows:
// like unordered_map but keeps the order of the elements for iteration
// implemented as a vector with a unordered_map for constant time lookups
// consider if element removal is needed, since it is O(N) because of the use of a vector of elements
template <typename KEY, typename VAL>
struct ordered_map {
struct KeyValue {
KEY key;
VAL value;
};
std::vector<KeyValue> elements; // KeyValue pairs in order of insertion to allow iteration
std::unordered_map<KEY, int> indexmap; // key -> index map to allow O(1) lookup, is there a way to avoid the redundant key?
//...
}
But I have the problem that in my approach I want to lookup into the indexmap using the keys which are stored 'externally' to it (in the elements vector based on the index value in the map).
std::sort
for example allows passing in a comparator,
but unordered_sap does not seem to have anything similar.
I could not really find anything online about how to accomplish this, but I might be searching with the wrong terms.
I this approach at all supported by the stl?
Or do I need to resort to storing the Key twice, which I would like to avoid as keys can be heap objects like std::strings for example.
EDIT: unordered_map instead of unordered_set which does not work