繁体   English   中英

为什么哈希 <const char*> 为字符串而不是字符串变量工作?

[英]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::stringconst 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.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM