散列表类

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;  
}

 

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值