哈希函数问题-添加功能 [英] Hash function issue - adding functionality

查看:45
本文介绍了哈希函数问题-添加功能的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我尝试向djb2哈希函数添加功能,但似乎不喜欢所做的更改.具体来说,我正在尝试包含一个将单词(字符串)转换为小写字母的循环.它将引发以下两个错误:

I tried adding functionality to the djb2 hash function, but it doesn't appear to like the changes. Specifically, I'm trying to include a loop that converts words (strings) to lower case. It throws the following two errors:

  1. 从指针到 int
  2. 分配给 char * 的指针转换不兼容的整数
  3. 无法递增类型为 char * [45]
  4. 的值
  1. Incompatible integer to pointer conversion assigning to char * from int
  2. Cannot increment value of type char *[45]

请注意,原始代码 * str ++ 出现在 while 循环中.这是我的第一个哈希表,并且我对指针有些不满意.任何关于我犯错地方的见解将不胜感激.

Note that in the original code *str++ appeared in the while loop. This is my first hash table, and I'm rather shaky on pointers. Any insight on where I've gone wrong would be appreciated.

// djb2 by Dan Bernstein -- slightly modified;
unsigned int hash_function(const char* str)
{
    unsigned int hash = 5381;
    int c;
    char* string[45];

    for (int i = 0; str[i] != '\0'; i++)
    {
        string[i] = (tolower(str[i]));
    }

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

    return (hash % LISTS);
}

推荐答案

哈希的更有效版本:

unsigned int hash_function(const char* str)
{
    unsigned int hash = 5381, c;
    while(c = *str++) 
      hash += (hash << 5) + (c | 040);

    return (hash % LISTS);
}

这篇关于哈希函数问题-添加功能的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆