loop a std::unordered_map, the sequence is always the sequence I insert elements?

1.3k Views Asked by At

I constructed a std::unordered_map and use for loop to visit it. I found that the sequence of the iteration result shows the elements is put in the sequence that I created those elements, no matter how I inserted them.

Is this part of C++ standard that unordered_map, when visited, the iteration sequence is the insertion sequence? Or this is implementation preference?

I ask this question is, I wish to know if this feature, is something I can rely in my c++ code?

1

There are 1 best solutions below

0
On BEST ANSWER

No. The standard makes no guarantees about the order of elements in the unordered associative containers (unordered map, set and their multivalued versions) and you can not rely on any particular ordering in your code.

Except for a special case [unord.req]/6 (standard draft, emphasis mine):

An unordered associative container supports unique keys if it may contain at most one element for each key. Otherwise, it supports equivalent keys. unordered_set and unordered_map support unique keys. unordered_multiset and unordered_multimap support equivalent keys. In containers that support equivalent keys, elements with equivalent keys are adjacent to each other in the iteration order of the container. Thus, although the absolute order of elements in an unordered container is not specified, its elements are grouped into equivalent-key groups such that all elements of each group have equivalent keys. Mutating operations on unordered containers shall preserve the relative order of elements within each equivalent-key group unless otherwise specified.