I am looking for a data structures that have the next features:
– have key and value
– can find the value in O(n) > t > O(logn ) or O(1)
– can pull the first element and the last element I insert.
TreeMep is not good, because if I insert key (as string) “b” and then key “a” if I will pull the first one I will get “a” instead of “b”
ConcurrentSkipListMap is not good because I can’t rely on size func’
will appreciate any help
thanks
You can use a
deque(double ended queue) cross-referenced with amultimap(tipically a binary search tree), which allows duplicate keys.Every element of the queue would have a reference (an iterator) to the corresponding element of the map and vice-versa.
This way, you can search in the map in O(log N) and you can push/pull at either ends of the sequence in O(log N).
You can decide to store the strings in the map or in the queue.
Here is an implementation in C++:
This also supports finding the index in the queue of any given key in O(log N). If you don’t need this, you can simplify the design storing the strings in the map and removing the references from the map to the queue.
Update: The key and value types are now specified via
typedefs. This way it’s easy to change them. It would be interesting to convert the whole thing in a template parametrized by these two types. This way, the same code would be reusable for different pairs of key-value types even in the same program.Update: There is a tool for the general case: the Boost Multi-index Containers Library. See this example in the documentation.