Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Are the elements in a std::map guaranteed to be ordered?

Tags:

c++

stl

Is this just an implementation side effect (red-black tree) or the order is guaranteed by the c++ standard?

like image 443
Thomson Avatar asked Jul 28 '10 03:07

Thomson


People also ask

Are std :: maps ordered?

are STL maps ordered? Yes, a std::map<K,V> is ordered based on the key, K , using std::less<K> to compare objects, by default.

Are C++ maps ordered?

By default, a Map in C++ is sorted in increasing order based on its key.

Is map always ordered?

Yes, std::map is a sorted container, ordered by the Key with the supplied Comparator . So it is guaranteed.

Does map store elements in sorted order?

A Map store the elements in the sorted order of keys. For example, we have a map of words and its frequency count as key – value pair i.e. Map internally stores the above elements in sorted order of keys i.e. Therefore, iterating over a map will give pair elements in above order.


1 Answers

Ordered iteration is not an implementation detail; it is guaranteed by the C++ standard. It is a fundamental property of all associative containers (C++03 §23.1.2/9):

The fundamental property of iterators of associative containers is that they iterate through the containers in the non-descending order of keys where non-descending is defined by the comparison that was used to construct them. For any two dereferenceable iterators i and j such that distance from i to j is positive,

    value_comp(*j, *i) == false

value_comp is the comparator with which the map was constructed (by default, it is std::less<T>).

like image 113
James McNellis Avatar answered Oct 13 '22 20:10

James McNellis