I try to find a way to get the same result when I hash a given string
in windows and in linux. but for example if I run the following code:
hash<string> h;
cout << h("hello");
it will return 3305111549 in windows and 2762169579135187400 in linux.
The results are correct. As mentioned in other answers, the C++ standard doesn't even guarantee that the values will be the same between various execution of the same program.
If it is not possible to get the same return value accross these 2
platforms, is there any other decent hash function that would return
the same value on both systems?
Yes!. You may want to check out Best hashing algorithms for speed and uniqueness for a list of good hash functions to implement.
However, after you select the one you want to use, you need one more extra guarantee: that the underlaying representations of characters are the same between the two platforms. That is that the numerical representations of 'a'
in platform 1 is same as 'a'
in platform 2. If one platform uses ASCII and the other uses a different encoding scheme, you aren't likely to get the same results.
Again, std::hash<>
already has a specialization for std::hash<std::string>
. So, other than your standard library's provision, there's nothing you can do about enforcing a behavior for the result of std::hash<std::string>()("hello")
. Your option is to use:
- a custom hash function-object, e.g
myNAMESPACE::hash<std::string>()("hello")
, or
- use a custom string type, and specialize it for
std::hash
; e.g std::hash<MyString>()("hello")