2016-11-18 23 views
0

私はC++でハッシュマップを実装しました。 ハッシュ関数を除いてすべて正常に動作します。さまざまなタイプのキーにハッシュ関数を実装する方法は?

私はハッシュマップにさまざまな変数型を使用できるように、要素のテンプレートクラスを持っています。 要素のコードです。

template <class KeyType, class ValType> 
class MapElem 
{ 
public: 
    typedef KeyType ktype; 
    typedef ValType vtype; 

    KeyType key; 
    ValType val; 

    MapElem* link; // singly linked list 
}; 

そして、ハッシュ関数コード。

template <class HashMapElemType> 
unsigned int 
HashMap<HashMapElemType>::hashfunction(const KeyType k) 
{ 
    unsigned int hashIndex = 0; 



    if (typeid(KeyType).name() == typeid(std::string).name()) 
    { 
     unsigned int hashIndex = 0; 

     const char* c = k.c_str(); 

     unsigned int i = 0; 
     int index = 0; 
     int shift = 0; 

     while (c[index] != '\0') 
     { 
      if (shift == 32) 
       shift = 0; 
      i += ((int) c[index++]) << shift; 
      shift += 8; 
     } 

     hashIndex = i; 
    } 
    else if (typeid(KeyType).name() == typeid(float).name()) 
    { 
     float f = k; 
     hashIndex = (unsigned int) f; 
    } 
    else if (typeid(KeyType).name() == typeid(int).name()) 
    { 
     int i = k; 
     hashIndex = (unsigned int) i; 
    } 
    else 
    { 
     hashIndex = k; 
    } 

    hashIndex = hashIndex % divisor; 

    return hashIndex; 
} 

ハッシュ関数に型キャストのコンパイルエラーがあります。私はなぜエラーが発生するのか理解していますが、修正方法はわかりません。 さまざまな種類のキー値からハッシュ値を取得する方法を知りました。

は、ああ、ここ enter image description here

+1

です...エラーはどこですか? – George

+0

typeidには名前があるので、任意の型を何かにキャストすることはできません。 if文は実行時に実行され、コンパイル時に型システムに影響を与えません。これらのコードパスはすべて、各キータイプごとにコンパイルする必要があり、必ずしも有効ではありません。おそらく、部分的に特殊化されたファンクタをしたいと思うでしょう。または多分あなたのエラーは完全に何か他のものです... – xaxxon

答えて

0

あなたのハッシュ関数は、あなたのコンテナクラスの外部に実装キータイプのテンプレート機能、あるべきエラーです。 これで、実際にハッシュマップを使用しているキータイプごとにテンプレート関数を特殊化できます。 これは、タイプチェックを実行時からコンパイル時に変え、より速く安全にします。

// hash function prototype, no implementation 
template<typename T> unsigned int CalculateHash(const T& v); 

// hash function specialization for std::string 
template<> unsigned int CalculateHash(const std::string& v) 
{ 
    // your hash function for std::string ... 
} 

コンテナの実装では、汎用ハッシュ関数を使用して、キーのハッシュ値を生成できます。

template <class HashMapElemType> 
unsigned int HashMap<HashMapElemType>::hashfunction(const KeyType& k) 
{ 
    // delegate to global hash function template 
    return ::CalculateHash<KeyType>(k); 
} 
+0

それは本当に助け、うまくいきます。どうもありがとうございました。 – Uni

+0

ようこそ。私はそれが助けてうれしいです。 – smocoder