unique STL container with special ordering

c++, containers, stl

Solution

There is no such container in the STL, although you can implement one with the existing containers by mixing a `std::set`/`std::unordered_set` (to check for uniqueness) and a `std::deque` (or any other sequence container) for the ordering.

Boost has multiindex containers that already do this for you if you can use it and want to take a look.

Problem

I have a need for a STL container which is capable of: 1) only storing unique items 2) has a guaranteed order based on when item was added to the container So, if I add items A, B, and C to my container in that order, A will always be accessible via: `myItems().begin()` or `myItems[0]` B will always be accessible via: `myItems.begin() + 1` or `myItems[1]` C will always be accessible via: `myItems.begin() + 2` or `myItems[2]` I am currently using an `unordered_set` which does not fulfill need #2. If I use a regular `set`, I can specify a less than function for ordering but the ordering may change as new items are added to the container. Using a regular `set`, if I insert a new item D which is less than A, A will no longer be accessible via `myItems.begin()`. I could be wrong but that is my understanding of how set ordering works. If I use a `list`, I can enforce the unique aspect by calling `list::unique()` after inserting every new item: ``` myList.sort(); myList.unique(); ``` or I could use `std::find` with a list or a vector and manually enforce the unique aspect: ``` iter = std::find(myList.begin(), myList.end(), item); //Only add item if not already in list/vector... if(iter == myList.end()) { myList.push_back(item); } ``` Is there a better container/solution for my particular needs?

Original source