2

The following code snippet can do hash value on a string object. I would like to get hash value a binary string (a pointer and length). I know I can form a string object with pointer and length, but there is extra overhead to form a string only for that. Wonder if it's possible to use the std hash function with two parameters: pointer and length.

Thanks.

#include <iostream>
#include <functional>
#include <string>

int main()
{
    std::string str = "Meet the new boss...";
    std::hash<std::string> hash_fn;
    std::size_t str_hash = hash_fn(str);

    std::cout << str_hash << '\n';
}
packetie
  • 4,839
  • 8
  • 37
  • 72
  • specialise std::hash for a custom class that holds a pointer and a length? – Richard Hodges Aug 22 '15 at 17:03
  • Thanks @RichardHodges for the comment, do you eventually need to call `std::hash()` to get the hash value? – packetie Aug 22 '15 at 17:13
  • @codingFun - You might want to look at [this answer to another question](http://stackoverflow.com/a/11639305/597607) to see how much time you save by not constructing a short `std::string` - about 1 ns. – Bo Persson Aug 22 '15 at 17:31

1 Answers1

2

I found this article in stack overflow which shows that the underlying hash function is actually a function of the bytes in the string's internal buffer:

What is the default hash function used in C++ std::unordered_map?

But rather than risk undefined behaviour by calling into internal functions within the standard library, why not ask the question, "how much performance will I lose by creating a std::string"? Given that you can always create such a string as a static const (zero overhead) I wonder what you're actually going to save?

Community
  • 1
  • 1
Richard Hodges
  • 68,278
  • 7
  • 90
  • 142
  • Thanks @RichardHodges for the link. Just tried, I can directly use: `std::_Hash_impl::hash(const char*, int size)`. :-) – packetie Aug 22 '15 at 17:19
  • 2
    Gah! You can today but there's no guarantee it will work on all systems or even on the next release of the library. It seems a little knowledge is a dangerous thing... – Richard Hodges Aug 22 '15 at 17:28
  • Agree. There is a trade off for everything :-) Thanks again. – packetie Aug 22 '15 at 22:49