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';
}
3
  • specialise std::hash for a custom class that holds a pointer and a length? Commented Aug 22, 2015 at 17:03
  • Thanks @RichardHodges for the comment, do you eventually need to call std::hash<string>() to get the hash value? Commented Aug 22, 2015 at 17:13
  • @codingFun - You might want to look at this answer to another question to see how much time you save by not constructing a short std::string - about 1 ns. Commented Aug 22, 2015 at 17:31

1 Answer 1

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?

Sign up to request clarification or add additional context in comments.

3 Comments

Thanks @RichardHodges for the link. Just tried, I can directly use: std::_Hash_impl::hash(const char*, int size). :-)
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...
Agree. There is a trade off for everything :-) Thanks again.

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.