Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

std::hash value on char* value and not on memory address?

Tags:

c++

c++11

hash

As stated in this link:

There is no specialization for C strings. std::hash produces a hash of the value of the pointer (the memory address), it does not examine the contents of any character array.

Which means that with the same char* value, different hashcodes could be produced. For example, having this code:

//MOK and MOV are template arguments
void emit(MOK key, MOV value) {
    auto h = hash<MOK>()(key);
    cout<<"key="<<key<<" h="<<h<<endl;
    ...

This is the output produced by calling 4 times emit() on the same key (with MOK=char*) value (but 4 different tokens/string objects):

key=hello h=140311481289184
key=hello h=140311414180320
key=hello h=140311414180326
key=hello h=140311481289190

How can I obtain the same hash code for char*? I'd prefer not to use boost

like image 820
justHelloWorld Avatar asked Jan 04 '16 18:01

justHelloWorld


2 Answers

You can use std::collate::hash e.g. https://www.cplusplus.com/reference/locale/collate/hash/

like image 172
aKumara Avatar answered Oct 04 '22 00:10

aKumara


In C++17 you should use std::hash<std::string_view> which works seamlessly since const char* can be implicitly converted to it.

like image 38
Artikash-Reinstate Monica Avatar answered Oct 03 '22 22:10

Artikash-Reinstate Monica