【问题标题】:Why is h*= h* 101 + s[i] and h = h * 101 + s[i] different in this case?为什么在这种情况下 h*= h* 101 + s[i] 和 h = h * 101 + s[i] 不同?
【发布时间】:2017-12-04 02:43:19
【问题描述】:

我只是好奇为什么这两个函数会产生不同的结果。

unsigned long Hash1(const string s)
{

    int length = s.length();
    unsigned long h = 1;

    for (int i = 0; i < length; i++)
        h *= 101 + (unsigned long)s[i];

    return h;
}

unsigned long Hash2(const string s)
{

    int length = s.length();
    unsigned long h = 1;

    for (int i = 0; i < length; i++)
        h = h * 101 + (unsigned long)s[i];

    return h;
}

int main()
{
    cout << "Value of hash1 = " << Hash1("kelvin@gmail.com") << endl;
    cout << "Value of hash2 = " << Hash2("kelvin@gmail.com") << endl;

    system("pause");
    return 0;
}

h *= 101 + (unsigned long)s[i] 不等于to h = h * 101 + (unsigned long)s[i]?

这是输出:

hash1 的值 = 1693843456

hash2 的值 = 2162085645

感谢您的帮助!!!

【问题讨论】:

  • 您没有h*= 101 或h = h * 101。你有h *= 101 + (unsigned long)s[i] 和h = h * 101 + (unsigned long)s[i]。
  • 你实际上是在告诉它..h = h * (101 + s[i]).. 换句话说,h = 自身乘以整个右侧表达式。

标签: c++ key hash-function


【解决方案1】:

h *= 101 + (unsigned long)s[i]不等于h = h * 101 + (unsigned long)s[i]吗?

不,由于operator precedence,h *= 101 + (unsigned long)s[i]等价于h *= (101 + (unsigned long)s[i]),与h = h * (101 + (unsigned long)s[i])相同。

两者的区别就是计算的区别:

h = h*(a+b)

和

h = h*a + b

【讨论】:

    【解决方案2】:

    问题的答案已经在 cmets 中给出,但只是为了扩展问题,两个 陈述

    h *= 101;
    
    h = h * 101;
    

    确实是等价的。但是当在较大的表达式中使用时,*= 的优先级很低。 * 的优先级最高,然后是 +,然后是 *=。所以

    h *= 101 + x;
    

    等同于:

    h = h * (101 + x);
    

    现在,如果你想要

    h = (h * 101) + x;
    

    你可以写:

    (h *= 101) += x;
    

    之所以有效,是因为*= 运算符返回对左侧的引用。但是,这看起来不太好。

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 2013-03-09
      • 1970-01-01
      • 2019-10-19
      • 2019-07-18
      • 2023-01-26
      • 1970-01-01
      • 1970-01-01
      • 2012-02-24
      相关资源
      最近更新 更多