沒有從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
由於'的std :: string'不是'爲const char *',並沒有適用的轉換運算符。使用'password.c_str()'。 [相關轉換問題](https://stackoverflow.com/questions/347949/how-to-convert-a-stdstring-to-const-char-or-char)。 – WhozCraig
因爲'string'不是'const char *'...爲什麼'cout << PassHash(42);'不工作? – immibis
ps的,如果你打算用這個實際的密碼 - 注意的std ::哈希並不在程序運行下一次一定會產生相同的輸出對於相同的輸入。 –