How to avoid sorting in map
Is there any way to avoid sorting of map on the basis of key value. Actually i want to disp开发者_运维问答lay all pair in same order i insert it into map.
Why not use a vector of pairs? That would suffice your requirement i guess
It seems what you require is two "views" of the data, one which maintains insert order and one which (presumably) you use for fast lookups. There is a structure which allows you to maintain this - if you can include boost. It's the boost multi_index container. You can specify two indexes, a hashed_unique
and ordered_unique
.
The way map is implemented internally, it's not possible for you to prevent keys to be sorted. However, you can maintain an additional list(using vector) to store the order in which keys appear. Later on, iterate over the map and the vector to achieve what you want.
No, there isn't. std::map<>
sorts by key to implement O(lg(n))
lookup.
You can get around with a std::vector<std::pair<Key,Value>>
to achieve what you need, but you'll need to write your own O(n)
lookup function to retrieve values by key.
I'm speculating here. Other would know for sure, but maps aren't stored in an array. It's more like a B-tree.
That means there is no way to know what record in the map was stored before or after another. Were I to build a map from scratch, I'd surely have no way to accomplish your task. Sorry.
Perhaps a map isn't your best option for storage. If you want to retrieve things in the order you've pushed them in, then perhaps a vector.
精彩评论