1. hash表需求: 哈希表(Hash table,也叫散列表),是根据关键码值(Key value)而直接进行访问的数据结构。也就是说,它通过把关键码值映射到表中一个位置来访问记录,以加快查找的速度。这个映射函数叫做散列函数,存放记录的数组叫做散列表。
2.参考《数据结构与算法分析c++ 描述》散列对于大数据量的查找,插入,删除以常数平均时间执行
实现如下,后续会对相关应用进行举例:
//散列:无排序
#include "iostream"
#include "vector"
#include "list"
#include "algorithm"
#include "string"
using namespace std;
//散列函数 //其中tableSize 是个常量
int hash(const string &key)
{
int hashVal = 0;
for(int i = 0; i < key.length(); i++)
{
hashVal = hashVal * 37 + key[i];
}
return hashVal;
}
//这个书上没有啊
int hash(int key)
{
return key;
}
/*
哈希表的数组是定长的,如果太大,则浪费,如果太小,体现不出效率。合适的数组大小是哈希表的性能的关键。
哈希表的尺寸最好是一个质数。当然,根据不同的数据量,会有不同的哈希表的大小。对于数据量时多时少的应
用,最好的设计是使用动态可变尺寸的哈希表,那么如果你发现哈希表尺寸太小了,比如其中的元素是哈希表尺
寸的2倍时,我们就需要扩大哈希表尺寸,一般是扩大一倍。
*/
static const int gPrimesCount = 10;
static unsigned long gPrimesArray[gPrimesCount] =
{
53, 97, 193, 389, 769,
1543, 3079, 6151, 12289, 24593
};
inline unsigned long nextPrime(unsigned long n)
{
const unsigned long *first = gPrimesArray;
const unsigned long *last = gPrimesArray + gPrimesCount;
const unsigned long *pos = lower_bound(first, last, n);
return pos == last ? *(last-1) : *pos;
}
//分离链接法, 散列表结构存储一个链表数组
template <typename HashedObj>
class HashTable
{
public:
explicit HashTable(int size = 101)
{
theLists.resize(size);
currentSize = size;
}
bool contains(const HashedObj &x) const;
void makeEmpty();
bool insert(const HashedObj &x);
bool remove(const HashedObj &x);
private:
vector <list<HashedObj>> theLists; //The array of Lists
int currentSize;
void rehash();
int myhash(const HashedObj &x) const;
};
template <typename HashedObj>
int HashTable<HashedObj>::myhash(const HashedObj &x) const
{
int hashVal = hash(x);
hashVal %= theLists.size();
if(hashVal < 0)
hashVal += theLists.size();
return hashVal;
}
template <typename HashedObj>
bool HashTable<HashedObj>::contains(const HashedObj &x) const
{
const list<HashedObj> &whichList = theLists[myhash(x)];
return find(whichList.begin(), whichList.end(), x) != whichList.end();
}
template <typename HashedObj>
void HashTable<HashedObj>::makeEmpty()
{
for(int i = 0; i < theLists.size(); i++)
theLists[i].clear();
}
template <typename HashedObj>
bool HashTable<HashedObj>::remove(const HashedObj &x)
{
list<HashedObj> &whichList = theLists[myhash(x)];
list<HashedObj>::iterator itr = find(whichList.begin(), whichList.end(), x);
if(itr == whichList.end())
return false;
whichList.erase(itr);
--currentSize;
return true;
}
template <typename HashedObj>
bool HashTable<HashedObj>::insert(const HashedObj &x)
{
list<HashedObj> &whichList = theLists[myhash(x)];
if(find(whichList.begin(), whichList.end(), x) != whichList.end())
return false;
whichList.push_back(x);
//rehash; see section 5.5
if(++currentSize > theLists.size())
rehash();
return true;
}
//散列表的重新构造
template <typename HashedObj>
void HashTable<HashedObj>::rehash()
{
vector<list<HashedObj>> oldLists = theLists;
//create new double-sized, empty table
theLists.resize(nextPrime(2*oldLists.size()));
for(int j = 0; j < theLists.size(); j++)
theLists[j].clear();
currentSize = 0;
for(int j = 0; j < oldLists.size(); j++)
{
list<HashedObj>::iterator itr = oldLists[j].begin();
while(itr != oldLists[j].end())
insert(*itr++);
}
}
template <typename HashedObj, typename Table>
void Test(HashedObj x, Table &table)
{
if(table.contains(x))
{
cout << typeid(table).name() << "contains "<< x << endl;
}
else
{
cout << typeid(table).name() << "not contains " << x << endl;
}
}
int main()
{
HashTable<int> IntTable;
IntTable.insert(10);
IntTable.insert(20);
IntTable.insert(30);
IntTable.insert(40);
IntTable.insert(50);
IntTable.remove(30);
IntTable.makeEmpty();
Test(20, IntTable);
Test(30, IntTable);
Test(40, IntTable);
Test(50, IntTable);
Test(60, IntTable);
Test(70, IntTable);
HashTable<string> StrTable;
StrTable.insert(string("10"));
StrTable.insert(string("20"));
StrTable.insert(string("30"));
StrTable.insert(string("40"));
Test(string("30"), StrTable);
Test(string("40"), StrTable);
Test(string("60"), StrTable);
Test(string("70"), StrTable);
cin.get();
cin.get();
return 0;
}
3.参考July <从头到尾彻底解析Hash 表算法> 的最快实现Hash表
//MPQ 中的Hash
//以下的函数生成一个长度为0X500(合10进制数:1280)的cryptTable[0x500]
void prepareCryptTable()
{
unsigned seed = 0x00100001, index1 = 0, index2 = 0, i;
for(index1 = 0; index1 < 0x100; index1++)
{
for(index2 = index1, i = 0; i < 5; i++, index2 += 0x100)
{
unsigned long temp1, temp2;
seed = (seed * 125 + 3) % 0x2AAAAB;
temp1 = (seed & 0xFFFF) << 0x10;
seed = (seed * 125 + 3) % 0x2AAAAB;
temp2 = (seed & 0xFFFF);
cryptTable[index2] = (temp1 | temp2);
}
}
}
//以下函数计算lpszFileName 字符串的hash值,其中dwHashType 为hash的类型,
unsigned long HashString(char *lpszFileName, unsigned long dwHashType)
{
unsigned char *key = (unsigned char*)lpszFileName;
unsigned long seed1 = 0x7FED7FED;
unsigned long seed2 = 0xEEEEEEEE;
int ch;
while(*key != 0)
{
ch = toupper(*key++); //转化为大写字母
seed1 = cryptTable[(dwHashType << 8) + ch]^(seed1 + seed2);
seed2 = ch + seed1 + seed2 + (seed2 << 5) + 3;
}
return seed1;
}
//每一个hash值通过取模运算(mod)对应数组中的一个位置,这样,
//只要比较这个字符串的哈希值对应的位置有没有被占用,就可得到最后的结果了
typedef struct
{
int nHashA;
int nHashB;
char bExists;
char *pString;
} SOMESTRUCTRUE;
//查找hash表中是否存在目标字符串,有则返回要查找字符串hash值,无则返回-1
int GetHashTable(char *lpszString, SOMESTRUCTRUE *lpTable)
//lpszString 要在hash表中查找字符串,lpTable为存储字符串Hash值的Hash表
{
int nHash = HashString(lpszString); //调用函数二,返回要查找字符串lpszString的Hah值
int nHashPos = nHash % nTableSize;
if(lpTable[nHashPos].bExists && !strcmp(lpTable[nHashPos].pString, lpszString))
{
//如果找到Hash值在表中存在,且要查找的字符串与表中的字符串相同
return nHashPos; //则返回上述调用函数二后, 找到的Hash值
}
else
{
return -1;
}
}
//函数四: lpszString 为要在hash表中那个查找的字符串;lpTable为存储字符串hash值的hash表;nTalbeSize 为hash表的长度
int GetHashTablePos(char *lpszString, SOMESTRUCTRUE *lpTable, int nTableSize)
{
const int HASH_OFFSET = 0, HASH_A = 1; HSAH_B = 2;
int nHash = HashString(lpszString, HASH_OFFSET);
int nHashA = HashString(lpszString, HASH_A);
int nHashB = HashString(lpszString, HASH_B);
int nHashStart = nHash % nTableSize;
int nHashPos = nHashStart;
while(lpTable[nHashPos].bExists)
{
/*如果仅仅是判断在该表中时候存在这个字符串,直接比较连个hash值就好,
不用比较两个的字符串,这样会加快速度?减少占用内存?适用于什么场合?*/
if(lpTable[nHashPos].nHashA == nHashA
&& lpTable[nHashPos].nHashB == nHashB)
{
return nHashPos;
}
else
{
nHashPos = (nHashPos + 1) % nTableSize;
}
if(nHashPos = nHashStart)
break;
}
return -1;
}
上述程序解释:
1.计算出字符串的三个哈希值(一个用来确定位置,另外两个用来校验)
2. 察看哈希表中的这个位置
3. 哈希表中这个位置为空吗?如果为空,则肯定该字符串不存在,返回-1。
4. 如果存在,则检查其他两个哈希值是否也匹配,如果匹配,则表示找到了该字符串,返回其Hash值。
5. 移到下一个位置,如果已经移到了表的末尾,则反绕到表的开始位置起继续查询
6. 看看是不是又回到了原来的位置,如果是,则返回没找到
7. 回到3