[英]Why does “auto” declare strings as const char* instead of std::string?
[英]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*>
模板实例化定义一个operator()
可以接受const char*
,这很简单,但是您要传递另一种类型的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*
。
例:
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
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.