Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Dynamically sorted STL containers

I'm fairly new to the STL, so I was wondering whether there are any dynamically sortable containers? At the moment my current thinking is to use a vector in conjunction with the various sort algorithms, but I'm not sure whether there's a more appropriate selection given the (presumably) linear complexity of inserting entries into a sorted vector.

To clarify "dynamically", I am looking for a container that I can modify the sorting order at runtime - e.g. sort it in an ascending order, then later re-sort in a descending order.

like image 235
dlanod Avatar asked Sep 15 '08 21:09

dlanod


People also ask

Is std set sorted?

Yes, std::set stores its elements in such a way that iterating over the elements will be done in sorted order (and the call to std::adjacent_find is to show that std::set stores unique items as well).

Which data structure is used for STL?

The Standard Template Library (STL) is a set of C++ template classes to provide common programming data structures and functions such as lists, stacks, arrays, etc. It is a library of container classes, algorithms, and iterators.


1 Answers

You'll want to look at std::map

std::map<keyType, valueType>

The map is sorted based on the < operator provided for keyType.

Or

std::set<valueType>

Also sorted on the < operator of the template argument, but does not allow duplicate elements.

There's

std::multiset<valueType>

which does the same thing as std::set but allows identical elements.

I highly reccomend "The C++ Standard Library" by Josuttis for more information. It is the most comprehensive overview of the std library, very readable, and chock full of obscure and not-so-obscure information.

Also, as mentioned by 17 of 26, Effective Stl by Meyers is worth a read.

like image 193
Doug T. Avatar answered Oct 18 '22 14:10

Doug T.