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

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

    You are missing a hash function for std::pair<int, int>>. For example,

    struct bad_hash
    {
      std::size_t operator()(const std::pair<int,int>& p) const
      {
        return 42;
      }
    };
    
    ....
    
    std::unordered_set< std::pair<int, int>, bad_hash> u_edge_;
    

    You can also specialize std::hash<T> for std::hash<std::pair<int,int>>, in which case you can omit the second template parameter.

    0 讨论(0)
  • 2020-12-08 00:55

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

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