gpt4 book ai didi

c++ - Dan Bernstein 为 C++ 编写的 djb2

转载 作者:行者123 更新时间:2023-11-30 01:20:04 26 4
gpt4 key购买 nike

我尝试从 C 代码翻译 djb2 哈希函数

unsigned long
hash(unsigned char *str)
{
unsigned long hash = 5381;
int c;

while (c = *str++)
hash = ((hash << 5) + hash) + c; /* hash * 33 + c */

return hash;
}

到 C++ 代码,但我有段错误。

int hf(std::string s){
unsigned long hash = 5381;
char c;
for(int i=0; i<s.size(); i++){
c=s[i++];
hash = ((hash << 5) + hash) + c; /* hash * 33 + c */
}
return hash;

我的错误在哪里?提前致谢

最佳答案

你想要 s[i],而不是 s[i++]。更好的方法是使用基于范围的 for。

int hf(std::string const& s) {
unsigned long hash = 5381;
for (auto c : s) {
hash = (hash << 5) + hash + c; /* hash * 33 + c */
}
return hash;
}

关于c++ - Dan Bernstein 为 C++ 编写的 djb2,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/19892609/

26 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com