Reputation: 907
boost::hash certainly works for std::string, but does it work for c string?
I've tried following code but the charHash(s2)
result changes every time I run the program. It seems boost::hash takes effect on the address of s2 instead of "Hello", so the hash result varies with the random address allocated by OS.
std::string s = "Hello";
char *s2 = "Hello";
boost::hash<std::string> stringHash;
boost::hash<char *> charHash;
cout << stringHash(s) << endl; // always "758207331"
cout <<charHash(s2) << endl; // it varies
Upvotes: 0
Views: 1354
Reputation: 64068
From the documentation:
As it is compliant with TR1, it will work with:
- integers
- floats
- pointers
- strings
It also implements the extension proposed by Peter Dimov in issue 6.18 of the Library Extension Technical Report Issues List (page 63), this adds support for:
- arrays
- std::pair
- the standard containers.
- extending boost::hash for custom types.
Basically, it is hashing the pointer. If you must hash a C-string, you could:
std::cout << stringHash(std::string(s2)) << std::endl;
// or the uglier...likely not equivalent
std::cout << boost::hash_range(s2, s2+strlen(s2)) << std::endl;
Upvotes: 3