Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Does std::unordered_map equality depend on insertion order

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.

like image 780
Raedwald Avatar asked Aug 06 '18 15:08

Raedwald


People also ask

Is order maintained in unordered_map?

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

Is unordered map sorted?

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.

How is unordered_map sorted?

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.

In what order elements are stored in unordered_map?

map (like set) is an ordered sequence of unique keys whereas in unordered_map key can be stored in any order, so unordered.


1 Answers

Yes, they're guaranteed to return equal in this case. The specific wording (from N4659, §[unord.req]/12) is:

Two unordered containers a and b compare equal if a.size() == b.size() and, for every equivalent-key group [Ea1, Ea2) obtained from a.equal_range(Ea1), there exists an equivalent-key group [Eb1, Eb2) obtained from b.equal_range(Ea1), such that is_permutation(Ea1, Ea2, Eb1, Eb2) returns true.

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.

like image 83
Jerry Coffin Avatar answered Oct 14 '22 15:10

Jerry Coffin