template <class DataType>
class HashTable
{
public:
HashTable(int (*pFunc)(const DataType &), int size);
bool Insert(const DataType &element);
bool Retrieve(DataType &element);
bool Remove(DataType &element);
void MakeEmpty();
private:
int position;
Array< LinkedList<DataType> > array; //动态数组内嵌单链表
int (*hashfunc)(const DataType &element); //散列函数应由主程序员自己生成,所以用一个函数指针。
};
template <class DataType>
HashTable<DataType>::HashTable(int (*pFunc)(const DataType &), int size)
:array(size)
{
hashfunc = pFunc;
}
template <class DataType>
bool HashTable<DataType>::Insert(const DataType &element)
{
position = hashfunc(element);
if((position<0) || (position>=array.GetSize()))
{
return false;
}
array[position].Insert(element);
return true;
}
template <class DataType>
bool HashTable<DataType>::Retrieve(DataType &element)
{
position = hashfunc(element);
if((position<0) || (position>=array.GetSize()))
{
return false;
}
if(!array[position].Retrieve(element))
{
return false;
}
return true;
}
template <class DataType>
bool HashTable<DataType>::Remove(DataType &element)
{
position = hashfunc(element);
if((position<0) || (position>=array.GetSize()))
{
return false;
}
if(!array[i].Remove(element))
{
return false;
}
return true;
}
template<class DataType>
void HashTable<DataType>::MakeEmpty()
{
int nLen = array.GetSize();
for(int i=0; i<nLen; i++)
{
array[i].MakeEmpty();
}
}
struct MyStruct
{
string str;
int num;
bool operator==(const MyStruct & r);
};
bool MyStruct::operator==(const MyStruct & r)
{
return str == r.str;
}
const int SIZE1=97,SIZE2=199;
int hash1(const MyStruct & obj);
int hash2(const MyStruct & obj);
void main()
{
HashTable<MyStruct> ht1(hash1,SIZE1),ht2(hash2,SIZE2);
MyStruct myjob;
myjob.str="elephant";
myjob.num=25;
ht1.Insert(myjob);
myjob.str="giraffe";
myjob.num=50;
ht1.Insert(myjob);
myjob.str="element";
myjob.num=80;
ht2.Insert(myjob);
MyStruct myjob2;
myjob2.str="element";
ht2.Retrieve(myjob2);
cout<<"myjob2.num:"<<myjob2.num<<endl;
myjob2.str="elephant";
ht1.Retrieve(myjob2);
cout<<"myjob2.num:"<<myjob2.num<<endl;
}
int hash1(const MyStruct & obj)
{
int sum=0;
for (int i=0;i<3 && i<int(obj.str.length());i++)
{
sum+=obj.str[i];
}
return sum % SIZE1;
}
int hash2(const MyStruct & obj)
{
int sum=0;
for (int i=int(obj.str.length())-1;i>-1 && i>int(obj.str.length())-7;i--)
{
sum+=obj.str[i];
}
return sum % SIZE2;
}