ChrisC
ChrisC

Reputation: 932

C+11 Associative Container that keeps insertion order?

is there, in the c++ "Standard Library", any "Associative" (i.e. "Key-Value") Container/Data Structure, that has the ability, to preserve order, by order of insertion?

I have seen several topics on this, however, it seems, most before C++11.

Some suggest using "boost::multi_index", but, if at all possible, I would "rather" use standard containers/structures.

I see that C++11 has several, apparently, "unordered" associative containers :link.

Are any of these, by some way, "configurable", such that they are only sorted by insertion order?

Thanks!

C

Upvotes: 7

Views: 3489

Answers (3)

user2181177
user2181177

Reputation:

No. In unordered maps too, there are not stored according to the order of insertion.

You can use vector to keep the track of the key!

Upvotes: 1

Potatoswatter
Potatoswatter

Reputation: 137810

No; such capability was apparently sacrificed in the name of performance.

The order of equivalent items is required to be preserved across operations including rehashes, but there's no way to specify the original order. You could, in theory, use std::rotate or the like to permute the objects into the desired order after each insertion. Obviously impractical, but it proves the lack of capability is a little arbitrary.

Your best bet is to keep the subsequences in inner containers. You may use an iterator adaptor to iterate over such a "deep" container as if it were a single sequence. Such a utility can probably be found in Boost.

Upvotes: 1

Ed Heal
Ed Heal

Reputation: 60007

No.

You are mixing linear access with random. Not very good bed fellows.

Just use both a vector/list (i.e. order of insertion) along with a map using an index into the former.

Upvotes: 3

Related Questions