Is iteration order of two unordered_set-s with same contents guaranteed to be the same

Viewed 125

If I have two unordered_set variables with same contents (if sorted), but created differently (say, first variable only had items inserted, second one had items inserted, erased, etc. in different order, but both variables ended up with same contents), will iterating over these two variables produce values in the same order?

PS. this question is different from similar questions on iterating same unordered set twice.

1 Answers

The standard does not make such guarantee. The ordering is bound to be implementation-specific.

Consider this example to see why the ordering may be different even though the content is identical: let's start with two unordered sets A and B that have been created and filled with values in the same order until a point when an addition of one more object would trigger rehashing.

Now consider what happens when add an object to B, and then remove it, while not adding any objects to A. Obviously, the two sets would be identical, but since B went through rehashing, the order of the objects in these sets would change.

Section 23.2.5.12 of the C++11 standard discusses the equality of unordered containers. It states that the worst-case time complexity of figuring out the equality is O(n^2). This implies that there is no guarantee of the same ordering, because otherwise we would be able to check equality in O(n).

Related