我不知道这是什么意思的代码. [英] A code, that I do not know what it meant.

查看:128
本文介绍了我不知道这是什么意思的代码.的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

你好.
此代码是做什么用的?
而"for"的目的是什么?

Hello.
What does this code do?
And what is the purpose of the "for" while?

int hash(const char *str) 
{
    if (str != 0)
    {
        unsigned h = str [0];
        for (int i = 1; str [i] != 0; ++i)
            h = (h << 5) - h + str [i];
        return h % HASH_SIZE; // remainder
    }
    else
    {
        return -1;
    }
}

推荐答案

这似乎是 djb2 [不同的常量 [此处 [
This seems to be the java string hashing algorithm[^]. It is a variant of the djb2[^] with different constants[^]. Here[^] you can find some explanation about the constants of djb2.


请参见此处 [ ^ ],以及之前和之后的页面.
See here[^], and preceding and succeeding pages.


尝试提供不同的字符串作为输入并查看输出是什么.随着for循环的进行,通过代码进行调试以检查h的不同值;当然,还有h的最终值.您需要在程序的开头定义HASH_SIZE.
Try giving different strings as input and seeing what the output is. And debugging through the code to inspect the different values of h as the for loop progresses; and, of course, the final value of h. You need to define HASH_SIZE towards the beginning in the program.


这篇关于我不知道这是什么意思的代码.的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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