Reputation: 388
is the output order of a map::iterator guaranteed if I don't change the keys/values in that map?
E.g., I initialize a map with some keys/values then do a sequence of loops and in each loop iterate over the map and perform read-only actions, will the output of each iteration be equal?
for(i=0;i<5;i++)
for(it=map.begin(); it!=map.end(); it++)
// read some value from map
Upvotes: 1
Views: 1701
Reputation: 6962
std::map
guarantees to be sorted. If contents don't change, map sorting shouldn't.
I can only think of a scenario in which this may not happen: map keys are pointers and comparison functor dereferences objects pointed by keys to perform comparison operations on them. Keys are not changed but values pointed by do (for any other reason). And even there I'm not sure if the standard forces implementation of std::map
to evaluate comparison only at the time of inserting elements.
Upvotes: 0
Reputation: 33655
the order is only modified on modify operations (insert, erase, clear), other operations will not impact the ordering
Upvotes: 0
Reputation: 791401
std::map
is an ordered collection. Iterating from begin()
to end()
will always return map entries in order.
The order is determined by the comparison operator of the map which is std::less<Key>
by default.
In a word: yes.
Upvotes: 12