I have a map which stores <int, char *>
. Now I want to retrieve the elements in the order they have been inserted. std::map
returns the elements ordered by the key instead. Is it even possible?
If you are not concerned about the order based on the int
(IOW you only need the order of insertion and you are not concerned with the normal key access), simply change it to a vector<pair<int, char*>>
, which is by definition ordered by the insertion order (assuming you only insert at the end).
If you want to have two indices simultaneously, you need, well, Boost.MultiIndex
or something similar. You'd probably need to keep a separate variable that would only count upwards (would be a steady counter), though, because you could use .size()+1
as new "insertion time key" only if you never erased anything from your map.
Now I want to retrieve the elements in the order they have been inserted. [...] Is it even possible?
No, not with std::map
. std::map
inserts the element pair into an already ordered tree structure (and after the insertion operation, the std::map has no way of knowing when each entry was added).
You can solve this in multiple ways:
use a std::vector<std::pair<int,char*>>
. This will work, but not provide the automatic sorting that a map does.
use Boost stuff (@BartekBanachewicz suggested Boost.MultiIndex)
Use two containers and keep them synchronized: one with a sequential insert (e.g. std::vector
) and one with indexing by key (e.g. std::map
).
use/write a custom container yourself, so that supports both type of indexing (by key and insert order). Unless you have very specific requirements and use this a lot, you probably shouldn't need to do this.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With