Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Why can't I use pair as key of unordered_set / unordered_map? [duplicate]

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.

like image 519
Rafer Avatar asked May 24 '15 03:05

Rafer


People also ask

Can a pair be a key in Unordered_map?

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.

Can we use pair in Unordered_set?

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.

Can Unordered_set have duplicate keys?

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.

Can Unordered_map have vector as key?

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.


1 Answers

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));
like image 125
Barry Avatar answered Oct 10 '22 15:10

Barry