#include "stdafx.h"

#ifdef _MSC_VER
#pragma hdrstop
#endif

using namespace std;

#include "myExcept.h"
#include "hashtable.h"

template<class T>
hashtable<T>::hashtable()
{
	data.resize(HASHSIZE);
	size = HASHSIZE;
	entries = 0;
}

template<class T>
hashtable<T>::hashtable( const unsigned int _size )
{
	data.resize(_size);
	size = _size;
	entries = 0;
}

template<class T>
hashtable<T>::~hashtable()
{
}

template<class T>
void hashtable<T>::clear(void)
{
	data.clear();
	data.resize(size);
	entries = 0;
}

template<class T>
unsigned int hashtable<T>::string2num(const string &key) const
{
	unsigned int num, i;

	num = 0;
	for ( i = 0; i < key.size(); i++ )
		num += key[i]*(i+100);
	return num;
}

template<class T>
void hashtable<T>::insert(const string &key, T item)
{
	data[string2num(key) % size].push_back(make_pair(key, item));
	entries++;
}

template<class T>
pair<bool, T> hashtable<T>::find(const string &key) const
{
	unsigned int numkey;
	list< pair<string, T > >::const_iterator it;
	T emptyres;

	numkey = string2num(key) % size;
	for ( it = data[numkey].begin(); it != data[numkey].end(); it++ )
		if ( (*it).first == key ) return make_pair(true, (*it).second);
	return make_pair(false, emptyres);
}

template<class T>
bool hashtable<T>::erase(const string &key)
{
	unsigned int numkey;
	list< pair<string, T > >::iterator it;

	numkey = string2num(key) % size;
	for ( it = data[numkey].begin(); it != data[numkey].end(); it++ )
		if ( (*it).first == key ) {
			data[numkey].erase(it);
			entries--;
			return true;
		}
	return false;
}
