c++中字符串到整型的哈希函数

Hash function in c++ for string to int

本文关键字:哈希 函数 整型 字符串 c++      更新时间:2023-10-16

我正在寻找c++中的哈希函数将字符串哈希为int。我使用CMapStringToPtr,但它有一个名为"GetNextAssoc"的函数,允许检索键作为字符串,这意味着字符串必须存储,它得到这么多的内存。有没有其他哈希函数占用更少的内存并且不存储字符串?

c++有一个内置的哈希函数,用于所有STL哈希容器。

std::hash

PS:你也可以自己制作,只需通过const引用传递字符串并逐个循环其字符,将它们添加到整数中,然后通过一些值进行mod:)

 int hash( const string &key, int tableSize) {
   int hashVal = 0;
   for(int i = 0; i<key.length();  i++)
     hashVal = 37*hashVal+key[i];
   hashVal %= tableSize;
   if(hashVal<0)
     hashVal += tableSize;
   return hashVal;
 }