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

Rafer picture Rafer · May 24, 2015 · Viewed 8.5k times · Source

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.

Answer

Barry picture Barry · May 24, 2015

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));