hash函数的C++实现
时间: 2023-10-22 10:55:26 浏览: 68
hash函数在C++中可以使用标准库中的哈希函数对象来实现。以下是一个简单的示例代码:
```cpp
#include <iostream>
#include <functional>
int main() {
std::hash<std::string> hash_fn; // 创建哈希函数对象
std::string input = "Hello, World!";
size_t hash_value = hash_fn(input); // 计算哈希值
std::cout << "Input: " << input << std::endl;
std::cout << "Hash value: " << hash_value << std::endl;
return 0;
}
```
这个示例使用了`std::hash`模板类来创建了一个哈希函数对象`hash_fn`,然后通过调用`hash_fn(input)`来计算输入字符串`input`的哈希值。最后将计算得到的哈希值打印出来。
请注意,这仅仅是一个简单的示例,实际应用中可能需要根据具体的需求选择更适合的哈希函数或自定义哈希函数。
相关问题
c++hash函数实现
以下是一个简单的C++哈希函数实现:
```c++
unsigned int hashFunction(const std::string& str)
{
unsigned int hash = 5381;
for (char c : str)
{
hash = ((hash << 5) + hash) + c; // hash * 33 + c
}
return hash;
}
```
该哈希函数使用了一个常见的算法,称为djb2算法。它将字符串转换为一个32位无符号整数哈希值。该算法使用一个称为“乘以33”的魔数,这是因为33是一个奇素数,可以确保哈希函数的均匀性。
c++hash函数头文件
C++ 中的哈希函数有很多种,但是没有一个标准的哈希函数库。不过,C++11 引入了一个新的哈希函数头文件 `functional` ,其中定义了两个模板类 `hash` 和 `hash_combine` ,可以用于自定义哈希函数。
以下是使用 `functional` 头文件定义哈希函数的示例代码:
```c++
#include <iostream>
#include <string>
#include <functional>
using namespace std;
struct Person {
string name;
int age;
};
class PersonHash {
public:
size_t operator()(const Person& p) const {
return hash<string>()(p.name) ^ hash<int>()(p.age);
}
};
int main() {
unordered_map<Person, int, PersonHash> m;
Person p1{"Alice", 20};
Person p2{"Bob", 25};
m[p1] = 1;
m[p2] = 2;
cout << m[p1] << endl;
cout << m[p2] << endl;
return 0;
}
```
在上面的示例代码中,我们定义了一个结构体 `Person` ,包含两个属性 `name` 和 `age` 。然后我们定义了一个类 `PersonHash` ,其中重载了圆括号运算符 `operator()` ,用于计算 `Person` 对象的哈希值。在 `operator()` 中,我们使用了 `hash` 模板类的默认哈希函数来计算 `name` 和 `age` 的哈希值,并使用异或运算符 `^` 将它们合并成一个哈希值。
最后,我们使用 `unordered_map` 容器来存储 `Person` 对象和对应的值,并使用自定义的哈希函数类 `PersonHash` 作为容器的第三个模板参数。
相关推荐
![application/x-rar](https://img-home.csdnimg.cn/images/20210720083606.png)
![pdf](https://img-home.csdnimg.cn/images/20210720083512.png)
![-](https://csdnimg.cn/download_wenku/file_type_column_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)