hash()函数的实现
輸入?yún)?shù)都是字符串。
6種hash函數(shù)的實現(xiàn)以及使用方式:
template<class T>
size_t BKDRHash(const T * str) // 該效率最高
{
?? ?register size_t hash = 0;
?? ?while (size_t ch = (size_t)*str++)
?? ?{
?? ??? ?hash = hash * 131 + ch; ? // 也可以乘以31、131、1313、13131、131313.. ? ? ? ??
?? ?}
?? ?return hash;
}
template<class T>
size_t SDBMHash(const T *str)
{
?? ?register size_t hash = 0;
?? ?while (size_t ch = (size_t)*str++)
?? ?{
?? ??? ?hash = 65599 * hash + ch;
?? ??? ?//hash = (size_t)ch + (hash << 6) + (hash << 16) - hash; ?
?? ?}
?? ?return hash;
}
template<class T>
size_t RSHash(const T *str)
{
?? ?register size_t hash = 0;
?? ?size_t magic = 63689;
?? ?while (size_t ch = (size_t)*str++)
?? ?{
?? ??? ?hash = hash * magic + ch;
?? ??? ?magic *= 378551;
?? ?}
?? ?return hash;
}
template<class T>
size_t APHash(const T *str)
{
?? ?register size_t hash = 0;
?? ?size_t ch;
?? ?for (long i = 0; ch = (size_t)*str++; i++)
?? ?{
?? ??? ?if ((i & 1) == 0)
?? ??? ?{
?? ??? ??? ?hash ^= ((hash << 7) ^ ch ^ (hash >> 3));
?? ??? ?}
?? ??? ?else
?? ??? ?{
?? ??? ??? ?hash ^= (~((hash << 11) ^ ch ^ (hash >> 5)));
?? ??? ?}
?? ?}
?? ?return hash;
}
template<class T>
size_t JSHash(const T *str)
{
?? ?if (!*str) ? ? ? ?// 這是由本人添加,以保證空字符串返回哈希值0 ?
?? ??? ?return 0;
?? ?register size_t hash = 1315423911;
?? ?while (size_t ch = (size_t)*str++)
?? ?{
?? ??? ?hash ^= ((hash << 5) + ch + (hash >> 2));
?? ?}
?? ?return hash;
}
template<class T>
size_t DEKHash(const T* str)
{
?? ?if (!*str) ? ? ? ?// 以保證空字符串返回哈希值0 ?
?? ??? ?return 0;
?? ?register size_t hash = 1315423911;
?? ?while (size_t ch = (size_t)*str++)
?? ?{
?? ??? ?hash = ((hash << 5) ^ (hash >> 27)) ^ ch;
?? ?}
?? ?return hash;
}
//6個仿函數(shù)分別進行6種字符串算法的調用
template<class T>
struct _HashFunc1
{
?? ?size_t operator()(const T& str)
?? ?{
?? ??? ?return BKDRHash(str.c_str());
?? ?}
};
template<class T>
struct _HashFunc2
{
?? ?size_t operator()(const T& str)
?? ?{
?? ??? ?return SDBMHash(str.c_str());
?? ?}
};?
template<class T>
struct _HashFunc3
{
?? ?size_t operator()(const T& str)
?? ?{
?? ??? ?return RSHash(str.c_str());
?? ?}
};?
template<class T>
struct _HashFunc4
{
?? ?size_t operator()(const T& str)
?? ?{
?? ??? ?return APHash(str.c_str());
?? ?}
};?
template<class T>
struct _HashFunc5
{
?? ?size_t operator()(const T& str)
?? ?{
?? ??? ?return JSHash(str.c_str());
?? ?}
};
template<class T>
struct _HashFunc6
{
?? ?size_t operator()(const T& str)
?? ?{
?? ??? ?return DEKHash(str.c_str());
?? ?}
};
?
總結
以上是生活随笔為你收集整理的hash()函数的实现的全部內容,希望文章能夠幫你解決所遇到的問題。
- 上一篇: A star算法
- 下一篇: 多线程死锁及解决办法