views:

292

answers:

5

It appears to from my simple testing but I'm wondering if this is guaranteed?

Are there conditions where the ordering will be not be guaranteed?

Edit: The case I'm particularly interested in is if I populate a map with a large number of entries, will the order of the itertator be the same across multiple runs of my executable? What if the entries are inserted in a different order?

A: 

Will an STL map give the same ordering with begin/end if it is unchanged? Yes. If you change the map though, do not depend on the ordering remaining the same.

JaredPar
...but the ordering of the unchanged elements remains the same--any insertions or deletions will be reflected at the appropriate place in the sequence per the ordering relation defined. That is to say, the changes to the map will change the iteration order in entirely predictable ways.
Drew Hall
A: 

On the same data set under the same implementation of STL, yes. It's not guaranteed to be the same across different implementations as far as I'm aware.

OJ
It's guaranteed to be the same across all implementation so long as the comparator provides a valid strict weak ordering--otherwise all bets are off!
Drew Hall
So it's guaranteed unless it's not? :)
OJ
+5  A: 

Yes, it maintains an internal order, so iteration over a set that isn't changing should always be the same. From here:

Internally, the elements in the map are sorted from lower to higher key value following a specific strict weak ordering criterion set on construction.

jeffamaphone
In glibc, it is a red-black tree.While strict ordering is not in the STL spec, it is the de facto standard.
J-16 SDiZ
@Jeffamaphone And if your key is a pointer to an object you can get any sort of ordering across multiple runs of your program.... well that explains that then doesn't it :)
Jamie Cook
@Jamie Cook: Technically, pointers aren't valid keys (at least with the default std::less comparator) since there is no operator< defined for pointers (though you can fake it by casting to unsigned long).
Drew Hall
+2  A: 

std::map is a sorted container, so, yes, order is guaranteed (the same as the ordering you use implicitly or explicitly in its constructor). Do not count on this for the popular (though not-yet-stanard) hashmap though -- it has very many advantages in many cases wrt std::map, but not a predictable order of iteration!

Alex Martelli
+1  A: 

std::map is a sorted collection
and you would have to define the less than operator
imagine m is a map of type T:

assert(m.size() > 1);
for (std::map<T>::const_iterator i = m.begin(); i != m.end(); ++i) {
    std::map<T>::const_iterator j = i + 1;
    while ( j != m.end() ) {
        assert(*i < *j);
        ++j;
    }
}
problem_solver