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?
Per the C++ standard, iteration over the elements in an std::set proceeds in sorted order as determined by std::less or by the optional comparison predicate template argument.
Unordered sets are containers that store unique elements in no particular order, and which allow for fast retrieval of individual elements based on their value. In an unordered_set, the value of an element is at the same time its key, that identifies it uniquely.
Use unordered_set when We need to keep a set of distinct elements and no ordering is required.
The time complexity of set operations is O(log n) while for unordered_set, it is O(1).
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.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With