Search code examples
c++c++11iterationunordered-set

Is order of iteration over the elements of std::unordered_set guaranteed to be always the same?


If iterate over the elements of std::unordered_set multiple times without changing the contents of the set (but potentially reading from it, calculating its size, etc.), is it guaranteed that the elements will be visited in the same order each time?


Solution

  • In the specific case you mention, yes. Because the standard is explicit about when re-hashing (and therefore re-ordering) takes place.

    It only happens during an insert.

    § 23.2.5 [unord.req]

    9 The elements of an unordered associative container are organized into buckets. Keys with the same hash code appear in the same bucket. The number of buckets is automatically increased as elements are added to an unordered associative container, so that the average number of elements per bucket is kept below a bound. Rehashing invalidates iterators, changes ordering between elements, and changes which buckets elements appear in, but does not invalidate pointers or references to elements. For unordered_multiset and unordered_multimap, rehashing preserves the relative ordering of equivalent elements.