为什么哈希<常量字符*>适用于字符串而不是字符串变量?
Why does hash<const char*> work for strings but not string variables?
我的问题是为什么以下代码有效
hash<const char*> PassHash;
cout << PassHash("Hello World");
但是此代码无法编译。
hash<const char*> PassHash;
string password;
password = "Hello World";
cout << PassHash(password);
在代码块中,我收到此错误
error: no match for call to '(__gnu_cxx::hash<const char*>) (std::string&)'|
std::hash
的定义类似于以下内容
template<typename T>
struct hash {
size_t operator()(const T& value) const {
...
}
}
因此,std::hash<const char*>
模板实例化定义了一个接受const char*
的operator()
,但您传递的是一个不同类型的std::string
,这很简单。
只需直接使用std::string
作为您的密码变量,然后改为std::hash<std::string>
。
没有从std::string
到const char*
的隐式转换,这是使您的示例正常工作所必需的。
您可以致电string::c_str()
明确执行此"转换"...
hash<const char*> PassHash;
string password;
password = "Hello World";
cout << PassHash(password.c_str());
。但这只会计算字符串指针的哈希值,因为hash<const char*>
没有专用化!因此,这仅与通用指针专用化hash<T*>
匹配。
您可能真正想要的是字符串的整个字符数组的哈希值,因此如果字符串的一个字符发生变化,您(很可能)会得到不同的哈希值。
为此,您可以使用hash<std::string>
专业化。这适用于const char*
和std::string
参数,因为 std::string 有一个采用const char*
的转换构造函数。
例:
const char* password1 = "Hello World";
string password2 = "Hello World";
hash<const char*> charPtrHasher;
// This only calculates a hash from the value of the pointer, not from
// the actual string data! This is why you get a different hash for each.
cout << "Test 1:n";
cout << charPtrHasher(password1) << endl << charPtrHasher(password2.c_str()) << endl;
hash<std::string> stringHasher;
// This correctly calculates the hash over all characters of the string!
cout << "nTest 2:n";
cout << stringHasher(password1) << endl << stringHasher(password2) << endl;
现场演示:http://coliru.stacked-crooked.com/a/047c099f5dcff948
相关文章:
- FLTK 2.0构建和演示,适用于VS2019的2011年左右的代码库
- C++17 - 使用自定义分配器的节点提取/重新插入 - 适用于 clang++/libc++,但不适用于 libstd
- "string.h"在构建适用于iOS的qt应用程序中找不到消息
- 组合字符串不适用于 libCurl,C++
- 适用于 WebView2 旧版本的示例应用程序
- 重载 std::字符串运算符+ 用于打印枚举名称
- 在 NVIDIA GEFORCE GTX 1050 上下载适用于 Windows 10 的 openCL 1.2
- __attribute__(优化(0))) 是否适用于"recursively"?
- 为什么 std::erase(std::erase_if) 不是适用于<algorithm>任何容器的模板?
- 使用一个参数的模板函数时出错(适用于 2)
- 使用 适用于 Android 和 iOS 的 tf-lite C++ API
- 为什么这适用于 G++ 而不是 CLANG?
- 适用于 macOS 的 Xcode 应用程序。这就是我设置从USB麦克风输入获取音频的方式。一年前工作,现在没有了。为什么
- 适用于 Linux 的 c++ 上的代理脚本
- 为什么我的 SFINAE 表达式不再适用于 GCC 8.2?
- 将wchar_t字符串从/传递到本机插件-仅适用于Windows
- C++11 正则表达式是否适用于 UTF-8 字符串
- 如何在 c++ 中将十六进制整数转换为字符串(适用于 html 颜色)
- 不在异常中嵌入std::字符串的规则是否仍然适用于move构造函数
- c++字符串操作,适用于iOS和Android平台