#include <iostream>
#include <cstdlib>
#include <cstring>
using namespace std;
template<class T> class hash;
template<>
class hash<string>
{
public:
size_t operator ()(const string &strKey) const
{
unsigned long longValue = 0;
int len = strKey.length();
for (int i = 0; i < len; i++)
{
longValue = 5 * longValue + strKey.at(i);
}
return size_t(longValue);
}
};
template <>
class hash<int>
{
public:
size_t operator() (int keyValue) const
{
return size_t(keyValue);
}
};
template<>
class hash<long>
{
public:
size_t operator() (long keyValue) const
{
return size_t(keyValue);
}
};
template<class K, class E>
class hashtable{
public:
hashtable(int divisor = 11);
~hashtable(){delete [] m_table;};
void insert(const pair<const K, E> &);
pair<const K, E>* find(const K &) const;
bool empty() const {return m_size == 0;}
int size() const {return m_size;}
void output(ostream &output) const;
protected:
pair<const K, E> **m_table;
int search(const K&) const;
hash<K> m_hash;
int m_size;
int m_divisor;
};
template<class K, class E>
hashtable<K, E>::hashtable(int divisor)
{
m_divisor = divisor;
m_size = 0;
m_table = new pair<const K, E>* [m_divisor];
for (int i = 0; i < m_divisor; i++)
{
m_table[i] = NULL;
}
}
template<class K, class E>
int hashtable<K, E>::search(const K& theKey) const
{
int j = (int)m_hash(theKey) % m_divisor;
int i = j;
do
{
if (NULL == m_table[i] || theKey == m_table[i]->first)
{
return i;
}
i = (i + 1) % m_divisor;
}while(i != j);
return i;
}
template<class K ,class E>
void hashtable<K, E>::insert(const pair < const K, E > & other)
{
int i = search(other.first);
if (NULL == m_table[i])
{
m_table[i] = new pair<const K, E>(other);
m_size++;
}
else
{
if (m_table[i]->first == other.first)
{
m_table[i]->second = other.second;
}
}
}
template<class K, class E>
pair<const K, E>* hashtable<K, E>::find(const K & theKey) const
{
int i = search(theKey);
if (m_table[i] == NULL)
{
return NULL;
}
else
{
if (m_table[i]->first == theKey)
{
return m_table[i];
}
}
return NULL;
}
template<class K, class E>
void hashtable<K, E>::output(ostream & output) const
{
for (int i = 0; i < m_divisor; i++)
{
if (NULL == m_table[i])
{
cout << "NULL" << endl;
}
else
{
cout << m_table[i]->first << " " << m_table[i]->second << endl;
}
}
}
/* reload */
template<class K, class E>
ostream& operator <<(ostream& out, const hashtable<K, E>& a)
{
a.output(out);
return out;
}
int main()
{
hashtable<string, int> myHash;
pair<string, int> p;
p.first = "wang";
p.second = 100;
myHash.insert(p);
p.first = "111";
p.second = 123;
myHash.insert(p);
cout << myHash;
cout << myHash.find("111")->second << endl;
char acIfname[32] = "oac_bi";
return 0;
}