问题
In other words, if I fill two unordered_map
, or unordered_set
, objects with exactly the same content and the same hashing function, will iterating over them give the same sequence of key/value pairs?
If so, then what are the conditions for this to hold (e.g. same hashing function, same keys, not necessarily same values).
回答1:
No. There is no requirement, for example, that objects that have the same hash be placed in any particular order. In fact, in general it's impossible for an unordered map to do this because the only information it has access to is the hash value.
回答2:
The behaviour in this case is undefined. So, in some situations the sequence will be the same, in others - different. You can't be sure in anything. The types you mentioned are named unordered not by accident. Using them as ordered ones is a very very bad and extremely dangerous style.
You can find that your compiler behaves in some special way you would like to use. But you can't be sure. You mustn't be sure! You do not know, what conditions are causing such behavior of the compiler. You can never be sure that any change of the compiler version will not change the behavior you need.
What is simply forbidden in other languages, in C/C++ is not specified. But you should take it as forbidden, too.
Look c-faq about the problem of undefined behavior This concept is common for all C/C++
回答3:
Well first I will quote MSDN:
The actual order of elements in the controlled sequence depends on the hash function, the comparison function, the order of insertion, the maximum load factor, and the current number of buckets. You cannot in general predict the order of elements in the controlled sequence. You can always be assured, however, that any subset of elements that have equivalent ordering are adjacent in the controlled sequence.
The above quote is the same for unordered_map
and unordered_set
and as the name implies the sequence is unspecified, however, they do mention that equivalent keys are adjacent.
回答4:
If you need guaranteed ordering, this is not the datastructure for you. In fact, if you're mainly going to be doing iteration, unordered_map/set
is not the data structre for you, either.
For iteration, a std::map
will prove to be the better data structure as gonig from one node to the next is less algorithmically complex. And the order of iteration for the objects in std::map
is guaranteed by the spec (and is actually a defining property of the structure itself). (This is all assuming you're using the same comparison operator, obviously). No hashing is involved in std::map
.
Suffice to say, it sounds like you're barking up the wrong tree here. unordered_map
should generally be using for the benefits such as O(1) lookup and not for storing a list of objects then iterating over them. It most definitely should not be used if you're trying to get a deterministic order of iteration.
来源:https://stackoverflow.com/questions/9856577/is-the-order-of-two-same-unordered-maps-the-same