【问题标题】:djb2 by Dan Bernstein for c++djb2 by Dan Bernstein for c++
【发布时间】:2013-11-22 10:38:34
【问题描述】:

我尝试从 c-code 翻译 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;

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

【问题讨论】:

    标签: c++ hash hash-function


    【解决方案1】:

    你想要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;
    }
    

    【讨论】:

    • 我有警告警告:'auto' 类型说明符是 C++11 扩展 [-Wc++11-extensions]
    • 使用-std=c++11。如果出于某种原因您不能使用 C++11,只需使用您的原始代码,但使用 s[i] 而不是 s[i++]
    • 对不起,你能详细解释一下吗,我需要在哪里使用它?我使用 Sublime Text 编译和运行程序。
    • 我已将 s[i++] 更改为 s[i] 并且仍然存在分段错误。
    • 这些(无论是剩余增量还是转换)都不是崩溃的原因,但它们会/可能导致不正确的哈希值。原始版本和 rightfold 大大改进的版本都必须工作 - 错误可能在其他地方。使用空字符串对象调用函数可能吗?
    【解决方案2】:

    这是我制作的一个非常快且对 c++ 友好的。

    unsigned long DJB2hash(string str)
    {
        unsigned long hash = 5381;
        unsigned int size  = str.length();
        unsigned int i     = 0;
        for (i = 0; i < size; i++) {
    
            hash = ((hash << 5) + hash) + (str[i]); /* hash * 33 + c */
        }
    
        return hash;
    }
    

    【讨论】:

      猜你喜欢
      • 2021-10-18
      • 2016-09-09
      • 2021-02-18
      • 2011-02-04
      • 1970-01-01
      • 2015-05-17
      • 1970-01-01
      • 2011-05-24
      • 1970-01-01
      相关资源
      最近更新 更多