1 int main() 2 { 3 const char* str = "one"; 4 int hashValue = 0; 5 while (*str != '\0') 6 { 7 hashValue = hashValue << 4 + *str; 8 ++str; 9 } 10 11 return 0; 12 }
hashvalue的值一直为0,何解?
因为 左移 运算符的优先级很低,所以上面的表达式结果时这样的:
1 hashValue = hashValue << (4 + *str);
正确姿势:
1 hashValue = (hashValue << 4) + *str;