Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Does the C++ standard library have a set ordered by insertion order?

Does the C++ standard library have an "ordered set" datastructure? By ordered set, I mean something that is exactly the same as the ordinary std::set but that remembers the order in which you added the items to it.

If not, what is the best way to simulate one? I know you could do something like have a set of pairs with each pair storing the number it was added in and the actual value, but I dont want to jump through hoops if there is a simpler solution.

like image 925
Seth Carnegie Avatar asked Oct 18 '11 00:10

Seth Carnegie


People also ask

Is std::set ordered?

Per the C++ standard, iteration over the elements in an std::set proceeds in sorted order as determined by std::less or by the optional comparison predicate template argument.

Does set in C++ maintain insertion order?

A set is the wrong container for keeping insertion order, it will sort its element according to the sorting criterion and forget the insertion order.

Are sets sorted by default in C++?

By default, values of the set are sorted in ascending order.

How does std::set work?

std::set is an associative container that contains a sorted set of unique objects of type Key . Sorting is done using the key comparison function Compare. Search, removal, and insertion operations have logarithmic complexity. Sets are usually implemented as red-black trees.


2 Answers

No single, homogeneous data structure will have this property, since it is either sequential (i.e. elements are arranged in insertion order) or associative (elements are arranged in some order depending on value).

The best, clean approach would perhaps be something like Boost.MultiIndex, which allows you to add multiple indexes, or "views", on a container, so you can have a sequential and an ordered index.

like image 138
Kerrek SB Avatar answered Sep 19 '22 15:09

Kerrek SB


Instead of making a std::set of whatever type you're using, why not pass it a std::pair of the object and an index that gets incremented at each insertion?

like image 20
pg1989 Avatar answered Sep 17 '22 15:09

pg1989