适用的字符串hash函数

下面是综合情况比较好的两个字符串hash函数,就当做一个笔记吧:

unsigned int BKDRHash(char *str)
{
	unsigned int seed = 131; // 31 131 1313 13131 131313 etc...
	unsigned int hash = 0;

	while (*str)
	{
		hash = hash * seed + (*str++);
	}

	return (hash & 0x7FFFFFFF);
}

unsigned int JSHash(char *str)
{
	unsigned int hash = 1315423911; // nearly a prime - 1315423911 = 3 * 438474637
	if (*str == 0x00)
	{
		return 0;
	}
	
	while (*str)
	{
		hash ^= ((hash << 5) + (*str++) + (hash >> 2));
	}
	
	return (hash & 0x7FFFFFFF);
}


整型hash函数:

static int _GetIndex(unsigned int addr)
{
 return (addr * 2654435769UL) >> 24;
}

static int indexFor(int hash, int length)
{
 return hash & (length - 1); //一般长度应为2的幂次方
}



  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
在C++中使用字符串hash函数加switch可以实现快速的字符串匹配,可以避免使用if-else语句进行逐个比对,从而提高程序的效率。具体实现步骤如下: 1. 定义字符串hash函数,将字符串转化为一个整数,可以使用STL中的hash函数或自己实现一个hash函数。 2. 在switch语句中使用hash值进行匹配,每个case语句匹配一个特定的hash值,从而实现字符串的匹配。 示例代码如下: ```c++ #include <iostream> #include <string> #include <functional> using namespace std; // 定义字符串hash函数 struct StrHash { size_t operator()(const string& str) const { return hash<string>()(str); } }; int main() { unordered_map<size_t, string> map = { {hash<string>()("hello"), "Hello World!"}, {hash<string>()("world"), "World Hello!"}, {hash<string>()("good"), "Good Morning!"}, {hash<string>()("night"), "Good Night!"} }; string str; cout << "Please enter a string: "; getline(cin, str); // 使用字符串hash值进行匹配 switch (hash<string>()(str)) { case hash<string>()("hello"): cout << map[hash<string>()("hello")] << endl; break; case hash<string>()("world"): cout << map[hash<string>()("world")] << endl; break; case hash<string>()("good"): cout << map[hash<string>()("good")] << endl; break; case hash<string>()("night"): cout << map[hash<string>()("night")] << endl; break; default: cout << "Unknown input!" << endl; break; } return 0; } ``` 注意:使用字符串hash函数加switch时,需要保证hash函数的唯一性,否则可能会出现hash冲突,导致匹配错误。

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值