tags:

views:

138

answers:

4

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

+2  A: 

It's guaranteed by the c++ standard.

Andrew Stein
It's great if you can point me to this part of standard.
Thomson Tan
A: 

Guaranteed. If you want something that's not constrained by this try boost::unordered_map<>

Daniel
Or, similarly, `std::tr1::unordered_map<>'.
+10  A: 

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>).

James McNellis
+1. Of course, this is not true for unordered types.
rlbond
@rlbond: True. However, C++03 has no unordered associative containers and in C++0x they are categorized separately ("associative containers" are separate from "unordered associative containers").
James McNellis
+4  A: 

§23.1.2/2:

Each associative container is parameterized on Key and an ordering relation Compare that induces a strict weak ordering (25.3) on elements of Key. … The object of type Compare is called the comparison object of a container. This comparison object may be a pointer to function or an object of a type with an appropriate function call operator.

The default Compare object is the less-than function std::less<Key>.

The ordering is a property of the function. It's a requirement, not a side effect.

Sorting the objects is a side effect. 23.1.2/10 and 23.1.2/9 (quoted by James) guarantee that map/set and multimap/multiset have increasing/non-decreasing keys, respectively, over the sequence from begin to end.

Potatoswatter