来自《数据结构与算法 王立柱》
//HashTable.h
#include<list>
#include<vector>
#include<iomanip>
#include<algorithm>
using namespace std;
template<class Iterator,class T>
Iterator Find(Iterator first,Iterator last,const T& x)
{
while(first!=last&&*first!=x)
{
++first;
}
return first;
}
template<class T>
class HashTable
{
private:
int nt;
vector<list<T> > ht;
int size;
int (*hf)(const T&x );
public:
explicit HashTable(int n,int (*hash)(const T& x)):nt(n),hf(hash),size(0){ht.resize(n);}
bool Insert(const T& x);
bool Remove(const T& x);
bool Find(const T& x)const;
int Size(void)const{return size;}
int Empty(void) const{return size==0;}
int NumberOfBucket(void)const{return nt;}
friend ostream& operator<<(ostream &ostr,const HashTable &ht)
{
int n=ht.NumberOfBucket();
list<T>::const_iterator first,last;
for(int i=0;i<n;i++)
{
first=ht.ht[i].begin(),last=ht.ht[i].end();
for(;first!=last;first++)
cout<<setw(4)<<*first<<' ';
cout<<endl;
}
return ostr;
}
};
template<class T>
bool HashTable<T>::Insert(const T&x)
{
list<T> &L=ht[hf(x)];
if(find(L.begin(),L.end(),x)!=L.end())
{
return 0;
}
L.push_back(x);
size++;
return 1;
}
template<class T>
bool HashTable<T>::Remove(const T&x)
{
list<T> & L=ht[hf(x)];
list<T>::iterator itr=find(L.begin(),L.end(),x);
if(itr==L.end())
{
return 0;
}
L.erase(itr);
size--;
return 0;
}
template<class T>
bool HashTable<T>::Find(const T&x)const
{
const list<T> &L=ht[hf(x)];
if(find(L.begin(),L.end(),x)!=L.end())
{
return 1;
}
return 0;
}
//main.cpp
#include<iostream>
#include"HashTable.h"
using namespace std;
int hf(const int &key)
{
return key%7;
}
int main()
{
HashTable<int> HT(7,hf);
for(int i=0;i<=27;i++)
{
HT.Insert(i);
}
cout<<HT<<endl;
cout<<"after moving :"<<endl;
if(HT.Find(20))
HT.Remove(20);
cout<<HT<<endl;
return 0;
}