#include <iostream>
#include <vector>
#include <list>
#include <algorithm>
#include <iterator>
bool isPrime(int x)
{
for(int i = 2; i * i <= x; ++i)
{
if(x % i == 0)
return false;
}
return true;
}
int nextprime(int x)
{
for(;;++x)
{
if(isPrime(x))
return x;
}
}
using namespace std;
template<class HashedObj>
class HashTable
{
public:
explicit HashTable(int size = 101);
bool contains(const HashedObj& x) const;
void makeEmpty();
bool insert(const HashedObj& x);
bool remove(const HashedObj& x);
void printtab() const;
private:
vector<list<HashedObj> > theLists;
int currentSize;
void rehash();
int myhash(const HashedObj& x) const;
int hash(const HashedObj& x) const;
};
template<class HashedObj>
HashTable<HashedObj>::HashTable(int size)
{
theLists.resize(size);
}
template<class 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<class HashedObj>
void HashTable<HashedObj>::makeEmpty()
{
for(size_t i = 0; i < theLists.size(); ++i)
theLists[i].clear();
}
template<class 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);
if(++currentSize > theLists.size())
rehash();
return true;
}
template<class HashedObj>
bool HashTable<HashedObj>::remove(const HashedObj& x)
{
list<HashedObj> &whichList = theLists[myhash(x)];
typename::list<HashedObj>::iterator itr = find(whichList.begin(), whichList.end(), x);
if(itr == whichList.end())
return false;
whichList.erase(itr);
--currentSize;
return true;
}
template<class HashedObj>
void HashTable<HashedObj>::rehash()
{
vector<list<HashedObj> > oldLists = theLists;
theLists.resize(nextprime(2 * theLists.size()));
for(size_t j = 0; j < theLists.size(); ++j)
theLists[j].clear();
currentSize = 0;
for(size_t i = 0; i < oldLists.size(); ++i)
{
typename list<HashedObj>::iterator itr = oldLists[i].begin();
while(itr != oldLists[i].end())
insert(*itr++);
}
}
template<class 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<class HashedObj>
void HashTable<HashedObj>::printtab() const
{
for(size_t i = 0; i < theLists.size(); ++i)
{
copy(theLists[i].begin(), theLists[i].end(), ostream_iterator<HashedObj>(cout, " "));
if(!theLists[i].empty())
cout << endl;
}
}
template<>
int HashTable<int>::hash(const int& x) const
{
return x % theLists.size();
}
template<>
int HashTable<string>::hash(const string& x) const
{
return x[0] % theLists.size();
}
int main()
{
return 0;
}
转载于:https://my.oschina.net/u/196018/blog/383771