C++哈希函数代码
时间: 2025-03-30 20:04:16 浏览: 52
### C++ 哈希函数实现示例
在 C++ 中,自定义哈希函数通常用于处理标准库中的容器(如 `unordered_map` 或 `unordered_set`),这些容器依赖于哈希函数来存储和检索数据。以下是基于引用内容以及实际应用的一个完整的哈希函数实现。
#### 使用字符串作为键的哈希函数
当键值为字符串时,可以采用一种简单的 BKDR 散列算法[^3]:
```cpp
#include <iostream>
#include <string>
#include <functional>
// 定义一个针对 std::string 的哈希函数
struct StringHash {
size_t operator()(const std::string& key) const {
size_t hash = 0;
for (char c : key) {
hash = hash * 31 + c; // BKDR 算法的核心部分
}
return hash;
}
};
int main() {
StringHash hasher;
std::string str1 = "hello";
std::string str2 = "world";
std::cout << "Hash of 'hello': " << hasher(str1) << std::endl;
std::cout << "Hash of 'world': " << hasher(str2) << std::endl;
return 0;
}
```
上述代码展示了如何通过重载 `operator()` 来创建一个仿函数对象,并将其应用于字符串类型的键值上。
---
#### 将自定义哈希函数集成到 STL 容器中
如果希望将该哈希函数与 STL 容器一起使用,则可以通过指定第三个模板参数完成配置。例如,在 `std::unordered_set<std::string>` 上使用自定义哈希函数:
```cpp
#include <iostream>
#include <unordered_set>
#include <string>
// 自定义哈希函数
struct CustomStringHash {
size_t operator()(const std::string& s) const {
size_t hash = 0;
for (char c : s) {
hash = hash * 31 + c; // BKDR 算法
}
return hash;
}
};
int main() {
// 创建 unordered_set 并传入自定义哈希函数
std::unordered_set<std::string, CustomStringHash> mySet;
mySet.insert("apple");
mySet.insert("banana");
if (mySet.find("apple") != mySet.end()) {
std::cout << "'apple' is found!" << std::endl;
}
return 0;
}
```
此代码片段演示了如何利用自定义哈希函数扩展 STL 容器的功能。
---
#### 更通用的哈希函数支持多种类型
为了使哈希函数更加灵活,还可以编写适用于不同数据类型的泛型版本。下面是一个基本框架[^1]:
```cpp
template<typename T>
struct GenericHash {
size_t operator()(const T& value) const {
return static_cast<size_t>(value); // 默认行为
}
};
// 特化版:专门处理 std::string 类型
template<>
struct GenericHash<std::string> {
size_t operator()(const std::string& value) const {
size_t hash = 0;
for (char c : value) {
hash = hash * 31 + c; // BKDR 算法
}
return hash;
}
};
```
这种设计允许开发者轻松扩展其他复杂的数据结构或类实例的支持。
---
### 总结
以上提供了几种典型的 C++ 哈希函数实现方式,涵盖了基础概念、具体应用场景及其与 STL 容器的结合方法。每种方案均经过精心设计以满足特定需求并保持高效性能[^2]。
阅读全文
相关推荐















