Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Does an STL map always give the same ordering when iterating from begin() to end()?

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?

like image 482
Jamie Cook Avatar asked Jun 11 '09 03:06

Jamie Cook


People also ask

Does map iterate in order?

The keys in Map are ordered in a simple, straightforward way: A Map object iterates entries, keys, and values in the order of entry insertion.

Is std::map always sorted?

Internally, the elements in a map are always sorted by its key following a specific strict weak ordering criterion indicated by its internal comparison object (of type Compare).

Are STL maps sorted?

Maps are associative containers that store elements in a mapped fashion. Each element has a key value and a mapped value. No two mapped values can have equal key values. By default, a Map in C++ is sorted in increasing order based on its key.

Does C++ map keep order?

C++ hash map and hash set which preserves the order of insertion. The ordered-map library provides a hash map and a hash set which preserve the order of insertion in a way similar to Python's OrderedDict. When iterating over the map, the values will be returned in the same order as they were inserted.


3 Answers

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.

like image 64
i_am_jorf Avatar answered Oct 26 '22 23:10

i_am_jorf


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!

like image 44
Alex Martelli Avatar answered Oct 26 '22 22:10

Alex Martelli


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;
    }
}
like image 36
problem_solver Avatar answered Oct 27 '22 00:10

problem_solver