【发布时间】:2018-08-28 01:01:09
【问题描述】:
我定义了一个名为Point 的类,它将用作unordered_map 中的键。所以,我在类中提供了一个operator== 函数,我还为std::hash 提供了一个template specialization。根据我的研究,这是我认为必要的两件事。相关代码如图:
class Point
{
int x_cord = {0};
int y_cord = {0};
public:
Point()
{
}
Point(int x, int y):x_cord{x}, y_cord{y}
{
}
int x() const
{
return x_cord;
}
int y() const
{
return y_cord;
}
bool operator==(const Point& pt) const
{
return (x_cord == pt.x() && y_cord == pt.y());
}
};
namespace std
{
template<>
class hash<Point>
{
public:
size_t operator()(const Point& pt) const
{
return (std::hash<int>{}(pt.x()) ^ std::hash<int>{}(pt.y()));
}
};
}
// Inside some function
std::unordered_map<Point, bool> visited;
程序编译并在我测试的情况下给出了正确的结果。但是,当使用用户定义的类作为键时,我不相信这是否足够。在这种情况下,unordered_map 如何知道如何解决冲突?我需要添加任何东西来解决碰撞吗?
【问题讨论】:
标签: c++ hashmap unordered-map user-defined-types hash-collision