我正在嘗試編寫一個在C++中使用散列表的程序。基本思想是我有很多數據點,並且我想使用散列表,以便給出一個新點,我可以知道它是否已經存在。但它有一些錯誤,我真的不知道如何解決它。 (錯誤消息:將'const Point'作爲'bool Point :: operator =='(const Point &)'this'的參數傳遞'丟棄限定符)在此先感謝。有關散列表的C++問題
#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;
}
然後它會給我另一個錯誤'未定義的引用std :: hash :: operator()(Point)const' –
Ming
你確實需要爲你的'Point'類定義一個哈希函數。 –
這個維基百科頁面描述瞭如何爲你的類寫一個哈希函數:http://en.wikipedia.org/wiki/Unordered_associative_containers_%28C%2B%2B%29#Custom_hash_functions –