如何使用c ++将一个字符串散列为一个int? [英] How can I hash a string to an int using c++?

查看:207
本文介绍了如何使用c ++将一个字符串散列为一个int?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我必须写我自己的哈希函数。如果我想只是使简单的哈希函数将字符串中的每个字母映射为一个数值(即a = 1,b = 2,c = 3,...),是有一种方式,我可以执行此哈希一个字符串,而不必先将其转换为c字符串来查看每个单独的char?有没有更有效的哈希字符串的方法?

I have to write my own hash function. If I wanted to just make the simple hash function that maps each letter in the string to a numerical value (i.e. a=1, b=2, c=3, ...), is there a way I can perform this hash on a string without having to first convert it to a c-string to look at each individual char? Is there a more efficient way of hashing strings?

推荐答案

重新提问第一个问题,例如: >

Re the first question, sure, e.g, something like:

int hash = 0;
int offset = 'a' - 1;
for(string::const_iterator it=s.begin(); it!=s.end(); ++it) {
  hash = hash << 1 | (*it - offset);
}

关于第二个,有很多更好的方法来哈希字符串。例如,请参阅这里几个C示例(可轻松地转换为C ++沿上面的代码段)。

regarding the second, there are many better ways to hash strings. E.g., see here for a few C examples (easily translatable to C++ along the lines of the snippet above).

这篇关于如何使用c ++将一个字符串散列为一个int?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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