簡體   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