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?

- 6,181
- 1
- 34
- 57
-
I know this is not the same but it is related: http://stackoverflow.com/questions/14346361/order-of-elements-in-stdunordered-multimap – NathanOliver Mar 26 '16 at 23:28
-
2It says "unordered" right in the name. – n. m. could be an AI Mar 26 '16 at 23:34
-
3@n.m. You misunderstood my question. I am not asking if the order can be predicted, but if its stable. – quant_dev Mar 26 '16 at 23:38
-
@NicolBolas So the answer is "no"? Is there an entry in the C++ spec which says that such questions as mine cannot be answered without snarky comments which add no value? – quant_dev Mar 26 '16 at 23:41
-
PS. "Why would a specification promise stability for something that isn't actually defined?" - it actually does so quite often. – quant_dev Mar 26 '16 at 23:41
-
Well, anyway, it turns out that the answer is "yes" ;-) – quant_dev Mar 26 '16 at 23:45
-
lol, i suppose the snarky comment author deleted it; sheesh! – luizfls May 03 '20 at 19:18
1 Answers
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.

- 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
-
-