【发布时间】:2011-02-01 21:05:56
【问题描述】:
我必须编写自己的哈希函数。如果我只想制作一个简单的哈希函数,将字符串中的每个字母映射到一个数值(即 a=1,b=2,c=3,...),有没有办法可以在一个字符串,而不必先将其转换为 c 字符串来查看每个单独的字符?有没有更有效的哈希字符串方法?
【问题讨论】:
我必须编写自己的哈希函数。如果我只想制作一个简单的哈希函数,将字符串中的每个字母映射到一个数值(即 a=1,b=2,c=3,...),有没有办法可以在一个字符串,而不必先将其转换为 c 字符串来查看每个单独的字符?有没有更有效的哈希字符串方法?
【问题讨论】:
您可以使用 [] 运算符检查 std::string 中的每个单独的字符。但是,您可以查看 Boost::Functional/Hash 以获得更好的散列方案的指导。 c 中还有一个哈希函数列表,位于here。
【讨论】:
您可以使用字符串类或迭代器的成员函数operator[] 或at 来访问字符串对象的单个字符,而无需将其转换为c 样式的字符数组。
要将字符串对象散列为整数,您必须访问字符串对象的每个单独的字符,您可以这样做:
for (i=0; i < str.length(); i++) {
// use str[i] or str.at(i) to access ith element.
}
【讨论】:
str.length(),尤其是对于在循环期间不会更改的散列字符串。此外,请考虑直接在str.c_str() 上工作,以避免在此进行任何函数调用。字符串确实以NULL 字符结尾。
将字符异或在一起,一次四个。
【讨论】:
当然是第一个问题,例如:
int hash = 0;
int offset = 'a' - 1;
for(string::const_iterator it=s.begin(); it!=s.end(); ++it) {
hash = hash << 1 | (*it - offset);
}
关于第二个,有很多更好的方法来散列字符串。例如,请参阅 here 了解一些 C 示例(可以按照上面的 sn-p 线轻松转换为 C++)。
【讨论】:
*2 和 | 来创建喜剧性差的哈希 ;-)
#include <iostream>
#include <string>
#include <algorithm>
using namespace std;
// a variation on dan bernstein's algorithm
// [http://www.cse.yorku.ca/~oz/hash.html]
template<typename Int>
struct hash {
hash() : acc(5381) { }
template<typename Ch>
void operator()(Ch ch) { acc = ((acc << 5) + acc) ^ ch; }
operator Int() const { return acc; }
Int acc;
};
int main(int argc, char* argv[])
{
string s("Hellp, world");
cout << hex << showbase
<< for_each(s.begin(), s.end(), hash<unsigned long long>()) << '\n';
return 0;
}
【讨论】:
这是我在 Stroustrup 的书中找到的 C (++) 哈希函数:
int hash(const char *str)
{
int h = 0;
while (*str)
h = h << 1 ^ *str++;
return h;
}
如果您将它用于哈希表(Stroustrup 就是这样做的),那么您可以改为返回以素数为模的哈希绝对值。所以改为
return (h > 0 ? h : -h) % N_BUCKETS;
最后一行。
【讨论】:
h 是 INT_MIN,评估 -h 会导致未定义的行为。最好使用无符号数字进行散列。
根据个人经验,我知道这很有效并且产生了良好的分布。 (抄袭自http://www.cse.yorku.ca/~oz/hash.html):
djb2
这个算法 (k=33) 是 dan bernstein 多年前在 comp.lang.c 中首次报道的。该算法的另一个版本(现在被 bernstein 青睐)使用 xor:hash(i) = hash(i - 1) * 33 ^ str[i];数字 33 的魔力(为什么它比许多其他常数工作得更好,无论是否素数)从未得到充分解释。
unsigned long hash(unsigned char *str) {
unsigned long hash = 5381;
int c;
while (c = *str++) {
hash = ((hash << 5) + hash) + c; /* hash * 33 + c */
}
return hash;
}
【讨论】:
小字符串的另一种方式:
int hash(const char* str) {
int hash = 0;
int c = 0;
while (c < std::strlen(str)) {
hash += (int)str[c] << (int)str[c+1];
c++;
}
return hash;
}
【讨论】:
C++11 附带了一个标准的字符串散列函数。
https://en.cppreference.com/w/cpp/string/basic_string/hash
#include <string>
#include<functional> // hash
int main(){
std::string s = "Hello";
std::size_t hash = std::hash<std::string>{}(s);
}
【讨论】:
刚刚发布了对 Arnestig 的 djb2 算法的改进,使其对 constexpr 友好。 我必须删除参数的无符号限定符,以便它可以处理文字字符串。
constexpr unsigned long hash(const char *str) {
unsigned long hash = 5381;
while (int c = *str++) {
hash = ((hash << 5) + hash) + c; /* hash * 33 + c */
}
return hash;
}
【讨论】: