4

I am looking for a container which provides std::map like interface but maintains the order in which elements are inserted. Since there will not be too many elements in the map, the lookup performance is not a big issue. Will boost::unordered_map work in this case? i.e. does it maintain the order of insertion. I am new to boost library and hence want to know what exactly meant by 'unordered' ?

philant
  • 34,748
  • 11
  • 69
  • 112
Naveen
  • 74,600
  • 47
  • 176
  • 233
  • Why not just try? :) experimentation isn't that bad. – LiraNuna Oct 22 '09 at 08:39
  • What are you trying to do? Check my answer to this other question and see if it applies: http://stackoverflow.com/questions/1570349/which-stl-container – Sam Harwell Oct 22 '09 at 08:42
  • 5
    @LiraNuna: Because that just tells you about the behavior in your current implementation and not whether this specific behavior is required and can be relied upon? – sbi Oct 22 '09 at 08:49

3 Answers3

19

Read about Boost.Multiindex. It gives you an opportunity to create a container that has both access to data by key (like std::map) and sequenced acess to data (like std::list).

This is an example.

9

unordered_map doesn't maintain the order of insertion. Unordered in this case means that the observable order of elements (i.e. when you enumerate them) is unspecified and arbitrary. In fact, I would expect that the order of elements in an unordered_map can change during the lifetime of the map, due to rehashing when resizing the map (that's implementation dependent though)

sbk
  • 9,212
  • 4
  • 32
  • 40
6

When I needed this last time, I used a std::vector< std::pair<const Key, Value> >. I didn't need much of the std::map interface so I didn't bother with is, but it seems it should be fairly easy to slap a map-like interface around this.

Also, be sure to look at the answers to this question.

Community
  • 1
  • 1
sbi
  • 219,715
  • 46
  • 258
  • 445