我正在尝试编写一个在C ++中使用哈希表的程序。基本的想法是我有很多数据点,我想使用一个哈希表,以便给出一个新点,我可以知道它是否已经存在。但它有一些错误,我真的不知道如何解决它。 (错误信息:传递'const Point'作为'bool Point :: operator ==(const Point&)的'this'参数'丢弃限定符)提前感谢。
#include <iostream>
#include <unordered_map>
using namespace std;
class Point {
public:
Point(int _x, int _y):x(_x), y(_y) {}
bool operator==(const Point& lhs)
{ return this->x==lhs.x && this->y ==lhs.y; }
private:
int x;
int y;
};
int main ()
{
Point p1=Point(1,2);
Point p2=Point(2,3);
Point p3=Point(4,5);
unordered_map<Point,bool> mymap = {{p1,true},{p2,true},{p3,true} };
Point p4=Point(1,2);
unordered_map<Point,bool>::const_iterator got = mymap.find(p4);
if (got == mymap.end())
cout << "not found";
else
cout << "already exists";
cout<<endl;
return 0;
}
答案 0 :(得分:3)
将operator==
本身声明为const
。
bool operator==(const Point& lhs) const // add this 'const' at the end
运算符函数的const
限定符告诉编译器this
也将被视为const
。
完成后,您需要为class Point
编写散列函数。你可以用两种方法之一。一种是制作专用的散列类,另一种是专门化std :: hash&lt;&gt;。这两种方法都在这里描述:http://en.wikipedia.org/wiki/Unordered_associative_containers_%28C%2B%2B%29#Custom_hash_functions
编辑:以下是为hash<Point>
提供模板专精的示例,该模板专门化回调Point
中的哈希方法。请注意,我写的散列函数是任意的 - 你应该试验并找出一个好的散列函数用于你的目的。
class Point {
public:
Point(int _x, int _y):x(_x), y(_y) {}
bool operator==(const Point& lhs) const
{ return this->x==lhs.x && this->y ==lhs.y; }
size_t hash() const
{
return (x * 0xAAAA) ^ (y * 0x5555);
}
private:
int x;
int y;
};
namespace std
{
template <> class hash<Point>
{
public:
size_t operator()( const Point &p ) const
{
return p.hash();
}
};
}
std::hash<Point>::operator()
回调Point::hash()
方法的原因是被散列的成员(x
和y
)是private
到Point
}。还有其他方法可以处理访问控制策略,但这看起来相当干净。
这个特定的协议(由std::hash<>
专业化转发的类中的散列成员)似乎适合于适配器范例。遗憾的是,我没有Josuttis的C ++ 11参考手册(http://www.cppstdlib.com/)的副本,看看我是否正在重新发明轮子......