开发者

std::map iterator output order will be constant if map keys/values don't change?

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 o开发者_开发问答f each iteration be equal?

for(i=0;i<5;i++)
 for(it=map.begin(); it!=map.end(); it++)
  // read some value from map


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.


the order is only modified on modify operations (insert, erase, clear), other operations will not impact the ordering


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.

0

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜