How do I use unordered_set?(如何使用 unordered_set?)
问题描述
I am trying to define an unordered_set like this:
unordered_set<Point> m_Points;
When I compile it, I get the following error:
The C++ Standard doesn't provide a hash for this type.
Class Point:
class Point{
    private:
        int x, y;
    public:
        Point(int a_x, int a_y)
            : x(a_x), y(a_y)
        {}
        ~Point(){}
        int getX()const { return x; }
        int getY()const { return y; }
        bool operator == (const Point& rhs) const{
            return x == rhs.x && y == rhs.y;
        }
        bool operator != (const Point& rhs) const{
            return !(*this == rhs);
        }
};
- How/where do I define a hash function for Point?
- What would be a good hash function for a 2D point?
std::unordered_set requires you to write hash functions to store and find your own types.
Base types and many types in the std namespace do have such hash functions within std::hash<Key>. These functions follow certain rules:
- Accepts a single parameter of type - Key.
- Returns a value of type - size_tthat represents the hash value of the parameter.
- Does not throw exceptions when called. 
- For two parameters - k1and- k2that are equal,- std::hash<Key>()(k1) == std::hash<Key>()(k2).
- For two different parameters - k1and- k2that are not equal, the probability that- std::hash<Key>()(k1) == std::hash<Key>()(k2)should be very small, approaching- 1.0/std::numeric_limits<size_t>::max().
Now that we got the definitions out of the way, let's think about what would be a good hash function for your point structure. There was a request that std::pair (which is very similar to a point structure) got a hash function, but, unfortunately, that did not make it into the C++11 standard.
But we are lucky: SO is awesome and, of course, you can basically already find the answer. Note that you do not have to hash integers yourself, because std::hash has a specialization for that already. So let's dig into our hash function, according to this answer:
namespace std
{
    template <>
    struct hash<Point>
    {
        size_t operator()(Point const & x) const noexcept
        {
            return (
                (51 + std::hash<int>()(x.getX())) * 51
                + std::hash<int>()(x.getY())
            );
        }
    };
}
And we are done.
这篇关于如何使用 unordered_set?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持编程学习网!
本文标题为:如何使用 unordered_set?
 
				
         
 
            
        基础教程推荐
- 如何检查GTK+3.0中的小部件类型? 2022-11-30
- 我有静态或动态 boost 库吗? 2021-01-01
- 如何将 std::pair 的排序 std::list 转换为 std::map 2022-01-01
- 这个宏可以转换成函数吗? 2022-01-01
- 如何在 C++ 中初始化静态常量成员? 2022-01-01
- 静态库、静态链接动态库和动态链接动态库的 .lib 文件里面是什么? 2021-01-01
- 如何通过C程序打开命令提示符Cmd 2022-12-09
- C++结构和函数声明。为什么它不能编译? 2022-11-07
- 常量变量在标题中不起作用 2021-01-01
- 在 C++ 中计算滚动/移动平均值 2021-01-01
 
    	 
    	 
    	 
    	 
    	 
    	 
    	 
    	 
						 
						 
						 
						 
						 
				 
				 
				 
				