簡體   English   中英

如何為各種類型的鍵實現哈希函數?

[英]How to implement the hash function for the various type of key?

我已經在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;
}

哈希函數中的類型轉換存在編譯錯誤。 我知道為什么會發生錯誤,但我不知道如何解決。 我想知道如何從不同類型的鍵值中獲取哈希值。

哦,這是錯誤,請在此處輸入圖片說明

您的哈希函數應該是密鑰類型上的模板函數,應在容器類之外實現。 然后,您可以為實際上使用哈希映射的每種鍵類型專門化模板功能。 這會將類型檢查從運行時轉變為編譯時,從而使其更快,更安全。

// 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 ); 
}

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM