How can I make an unordered set of pairs of integers in C++?

前端 未结 8 1452
陌清茗
陌清茗 2020-12-08 00:16

The following program does not compile an unordered set of pairs of integers, but it does for integers. Can unordered_set and its member functions be used on us

8条回答
  •  挽巷
    挽巷 (楼主)
    2020-12-08 00:43

    The problem is that std::unordered_set is using std::hash template to compute hashes for its entries and there is no std::hash specialization for pairs. So you will have to do two things:

    1. Decide what hash function you want to use.
    2. Specialize std::hash for your key type (std::pair) using that function.

    Here is a simple example:

    #include 
    
    namespace std {
    template <> struct hash> {
        inline size_t operator()(const std::pair &v) const {
            std::hash int_hasher;
            return int_hasher(v.first) ^ int_hasher(v.second);
        }
    };
    
    }
    
    int main()
    {
        std::unordered_set< std::pair > edge;
    }
    

提交回复
热议问题