哈希表类(HashTable)
#include "array.h"
#include "list.h"
#include "link.h"
#include "iterator.h"
template
class HashTableIterator;
template
class HashTable:public List
{ protected:
int numBuckets; //哈希表大小,桶的个数
Array > buckets; //哈希表为链表构成的数组的"桶"
unsigned long (*hf)(T key); //哈希函数
T *current; //指向当前数据项的指针
public:
HashTable(int nbuckets,unsigned long hashf(T key)); //构造函数:哈希表大小及哈希函数
virtual void Insert(const T& key);
virtual int Find(T& key);
virtual void Delete(const T& key);
virtual void ClearList(void);
void Update(const T& key); //对已在哈希表中的元素进行更新
friend class HashTableIterator; //相关的迭代算子可以访问数据成员
};
struct NameRecord
{ String name;
int count;
}
//一个可存放101个元素的哈希表,其哈希函数为hash
HashTable HF(101,hash);
NameRecord rec;
rec.name="Betsy";
rec.count =1;
HF.Insert(rec); //插入记录
cout<
rec.name="Betsy";
if(HF.Find(rec))
{ rec.count +=1;
HF.Update(rec); //存回哈希表中
}else
cerr<<"Error:\"Betsy should be in the talble.\"\n";
HashTableIterator类:(无序)
class HashTableIterator:public Iterator
{ private:
HashTable *hashTable;
int currentBucket; //桶的下标
LinkedList *currBucketPtr; //链表“桶”当前指针
void SearchNextNode(int cb); //取下一个结点的例程,cb是表下标;如果cb>hashTable->numBuckets,终止检索,扫描结束,
public:
HashTableIterator(HashTable &ht);
virtual void Next(void);
virtual void Reset(void);
virtual T& Data(void);
void SetList(HashTable & lst); //用迭代算子遍历另外一个表
}
//Hash表的遍历
HashTableIterator hiter(HF);
for(hiter.Reset();!hiter.EndOfList();hiter.Next())
{ rec=hiter.Data();
cout<
}
串哈希函数:
unsigned long hash(NameRecord elem)
{ unsigned long hashval=0;
for(int i=0;i
{ hashval=(hashval<<3)+elem.name[i]; //将当前哈希值左移三位后加上下一字符
}
return hashval;
}
编辑明升娱乐城:http://www.