I understand the mathematical basis for hash tables. I have a hash function (that I found somewhere) below:
/* Fowler / Noll / Vo (FNV) Hash */
static const size_t InitialFNV = 2166136261U;
static const size_t FNVMultiple = 16777619;
size_t myhash(const string &s, int length)
{
size_t hash = InitialFNV;
for(size_t i = 0; i < length; i++)
{
//XOR the lower 8 bits
hash = hash ^ (s[i]);
//Multiply by the multiple
hash = hash * FNVMultiple;
}
return hash;
}
size_t
? store()
function which places a string in a hash table? for
loop with a while
loop that terminates at the '\\0'
character? FYI, I am studying up for a second job interview, and that's why I'm asking.
It returns size_t
because that's the native integer (also fastest). Why choose anything else?
"The table"? Which table? If you mean a hashtable, then you can use the return value to choose a random bucket to put the object in. (Hint: Think "remainder".)
Isn't it already adapted for an array?
If it's a null-terminated string, why not?
It doesn't have to be size_t
, but it should probably be an unsigned integer type so mod is well-defined.
The usual way is to use the hash function to transform the 'key' data into an array index. So you mod by the size of the array to get an integer from 0 to SIZE-1 that you can use as an index. You'll also need a "collision resolution strategy" because unless the hash yields perfect results, some pairs of keys which are different will hash to the same value.
It appears already to be so adapted.
If the string ends in NUL, you can search for the null. But the function as written is passed a length as argument. Simplest to leave the working function alone, and call it with the result of strlen().
Ps. the const string &s
means C++, not C. This may be important when compiling.
string
holds it's own length, you don't need it to be passed in. That's C++, not C- no references in C. There's no need for strlen
or anything like that, or NULL
terminators, or anysuch. That means that replacing it with a while loop looking for \\0
would be Bad™, as there's no guarantee that std::string
even has one, let alone has it as it's terminator.
The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.