温馨提示×

C++ Hashtable如何自定义哈希函数

c++
小樊
88
2024-07-21 03:36:04
栏目: 编程语言

要自定义哈希函数,需要实现一个哈希函数对象,并将其作为模板参数传递给unordered_map或unordered_set。以下是一个简单的示例:

#include <iostream>
#include <unordered_map>
#include <string>

struct MyHashFunction {
    std::size_t operator()(const std::string& str) const {
        // 自定义哈希函数,这里简单地返回字符串长度作为哈希值
        return str.length();
    }
};

int main() {
    std::unordered_map<std::string, int, MyHashFunction> myMap;

    myMap["apple"] = 5;
    myMap["banana"] = 10;

    std::cout << "apple: " << myMap["apple"] << std::endl;
    std::cout << "banana: " << myMap["banana"] << std::endl;

    return 0;
}

在上面的示例中,我们定义了一个名为MyHashFunction的结构体,重载了operator()函数来自定义哈希函数。然后在创建unordered_map时,将MyHashFunction作为第三个模板参数传递给unordered_map,这样就可以使用自定义的哈希函数来计算键的哈希值了。

当插入或查找键时,unordered_map会使用自定义的哈希函数来计算对应的哈希值,从而确定元素在哈希表中的位置。

0