2013-11-04 126 views
2

我正在嘗試編寫一個在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; 
} 

回答

3

聲明operator==本身const

bool operator==(const Point& lhs) const // add this 'const' at the end 

const預選賽運營商的功能告訴this也將被視爲const編譯器。

一旦你這樣做了,你需要編寫一個散列函數class Point。你可以通過以下兩種方式之一來完成。一個是做一個專門的哈希類,另一個是專門化std :: hash <>。這兩種方法在這裏描述: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()方法是,構件被散列(xy)是privatePoint。還有其他方式來處理訪問控制策略,但這似乎相當乾淨。

這個特殊的協議(通過std::hash<>專業化轉發給類中的哈希成員)看起來好像適用於適配器範例。我不幸沒有我的Josuttis的C++ 11參考手冊(http://www.cppstdlib.com/)的副本,看看我是否在重新發明輪子...

+0

然後它會給我另一個錯誤'未定義的引用std :: hash :: operator()(Point)const' – Ming

+0

你確實需要爲你的'Point'類定義一個哈希函數。 –

+0

這個維基百科頁面描述瞭如何爲你的類寫一個哈希函數:http://en.wikipedia.org/wiki/Unordered_associative_containers_%28C%2B%2B%29#Custom_hash_functions –