Both std::set<>
and std::map<>
can use a std::pair
as a key, but why can't std::unordered_set<>
and std::unordered_map<>
?
For example:
unordered_set<pair<int,int> > S;
S.insert(make_pair(0, 1));
Does not compile.
Unordered Map does not contain a hash function for a pair like it has for int, string, etc, So if we want to hash a pair then we have to explicitly provide it with a hash function that can hash a pair. unordered_map can takes upto 5 arguments: Key : Type of key values.
An unordered set of pairs is an unordered set in which each element is a pair itself. By default, C++ doesn't allow us to create an unordered set of pairs directly but one can pass a hash function to the unordered set container.
Keys are immutable, therefore, the elements in an unordered_set cannot be modified once in the container - However, they can be inserted and removed. Unordered sets do not allow duplicates and are initialized using comma-delimited values enclosed in curly braces.
unordered_map uses vector as the key You can use the following method if you'd like to make the best of STL. }; Note that you can use any kind of operation to generate a hash. You just need to be creative so that collisions are minimized.
The unordered_*
containers need a hash function. By default, they use std::hash
but there is no specialization of std::hash
for std::pair<T1,T2>
provided in the standard library. On the other hand, the ordered containers rely on std::less
(by default) and std::pair
does have operator<
provided. That's why it just works.
In order to have an unordered container with a pair
, you will have to provide a hash functor yourself. For example:
struct SimpleHash {
size_t operator()(const std::pair<int, int>& p) const {
return p.first ^ p.second;
}
};
std::unordered_set<std::pair<int, int>, SimpleHash> S;
S.insert(std::make_pair(0, 1));
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