If you create two std::unordered_map
containers using the same set of (non equal) key-value pairs, but inserted in a different order (so the containers hold equal elements, but potentially in different orders), are the containers guaranteed to be equal, according to the equality operator (operator==
). I'm assuming that the hash-code and equality operators of the container elements satisfy all the required constraints on their implementation.
No, it is not possible. Usage of std::unordered_map doesn't give you any guarantee on element order. If you want to keep elements sorted by map keys (as seems from your example) you should use std::map . If you need to keep list of ordered pairs you can use std::vector<std::pair<std::string,int>> .
Unordered map is an associative container that contains key-value pairs with unique keys. Search, insertion, and removal of elements have average constant-time complexity. Internally, the elements are not sorted in any particular order, but organized into buckets.
An unordered_map is a hash container, that is, the keys are hashed. Inside of the container, they don't have the same representation as on the outside. Even the name implies that you can't sort it. It's one of the criteria to choose a hash container: You do not need a specific order.
map (like set) is an ordered sequence of unique keys whereas in unordered_map key can be stored in any order, so unordered.
Yes, they're guaranteed to return equal in this case. The specific wording (from N4659, §[unord.req]/12) is:
Two unordered containers
a
andb
compare equal ifa.size() == b.size()
and, for every equivalent-key group[Ea1, Ea2)
obtained froma.equal_range(Ea1)
, there exists an equivalent-key group[Eb1, Eb2)
obtained fromb.equal_range(Ea1)
, such thatis_permutation(Ea1, Ea2, Eb1, Eb2)
returnstrue
.
So, as long as the keys (and associated values) in one are the same as the other (but possibly in a differently-permuted order), it will compare equal.
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