[英]Why does a hash function return a size_t, and how is it used?
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
? size_t
? store()
function which places a string in a hash table? store()
字符串放在哈希表中的store()
函数? for
loop with a while
loop that terminates at the '\\0'
character? '\\0'
字符的while
循环替换for
循环是否合适? 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). 它返回
size_t
因为这是本机整数(也是最快的)。 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? 如果它是一个以null结尾的字符串,为什么不呢?
It doesn't have to be size_t
, but it should probably be an unsigned integer type so mod is well-defined. 它不一定是
size_t
,但它应该是无符号整数类型,因此mod是明确定义的。
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.
因此,您可以通过数组的大小来修改从0到SIZE-1的整数,您可以将其用作索引。 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. 如果字符串以NUL结尾,则可以搜索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().
最简单的方法是单独保留工作函数,并使用strlen()的结果调用它。
Ps. PS。 the
const string &s
means C++, not C. This may be important when compiling. const string &s
表示C ++, 而不是 C.这在编译时可能很重要。
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. string
保存它自己的长度,你不需要传入它。那是C ++,而不是C- C中没有引用。不需要strlen
或类似的东西,或NULL
终结符,或者它们。 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. 这意味着用一个寻找
\\0
的while循环替换它将是Bad™,因为不能保证std::string
甚至有一个,更不用说它是它的终止符。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.