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

前端 未结 8 1472
陌清茗
陌清茗 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:55

    You need to provide a specialization for std::hash<> that works with std::pair. Here is a very simple example of how you could define the specialization:

    #include 
    #include 
    
    namespace std
    {
        template<>
        struct hash>
        {
            size_t operator () (std::pair const& p)
            {
                // A bad example of computing the hash, 
                // rather replace with something more clever
                return (std::hash()(p.first) + std::hash()(p.second));
            }
        };
    }
    
    class A
    {
    private:
        // This won't give you problems anymore
        std::unordered_set< std::pair > u_edge_;
    };
    

提交回复
热议问题