10

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?

quant_dev
  • 6,181
  • 1
  • 34
  • 57

1 Answers1

9

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.

Richard Hodges
  • 68,278
  • 7
  • 90
  • 142
  • Thanks, a great answer from someone who actually knows what he's talking about :) – quant_dev Mar 26 '16 at 23:42
  • 1
    @quant_dev One thing to be careful of is during `erase`, order is only guaranteed to be preserved as of c++14. In c++11 you could not portably erase items in a for loop because each erase had the potential to reorder the map. If you're using c++11 (and can't upgrade) then use `erase_if` instead and remember that the map may have been reordered as a result. – Richard Hodges Mar 26 '16 at 23:48
  • I don't need to erase. Thanks. – quant_dev Mar 26 '16 at 23:52
  • @RichardHodges Do you mean `remove_if`? – luizfls May 03 '20 at 19:17