建立了一个hashmap类,该类的key必须大于0,用一个vector模拟hashmap.
写了build, insert 和delete 的函数。
目前,采用的是链式hash,就是相同的key的元素存放在一个数组中,目前用STL库中自带的vector类实现,以后,可以考虑用list实现。
代码如下:
// OOD.cpp : 定义控制台应用程序的入口点。
//
#include "stdafx.h"
#include<iostream>
#include<vector>
using namespace std;
/*implement the hash table using list*/
template<typename T>
struct hashelem
{
int key;
vector<T> valuearray;
hashelem()
{
key = -1;
}
};
template<class T>
class hashmap
{
public:
hashmap();
~hashmap();
int cal_key_value(T elem); // calculate hash key
vector<hashelem<T>> buildhashtable(vector<T> elemarray);
void hashinsert(T elem);
void hashdelete(T elem);
private:
int capcity;
int used;
vector<hashelem<T>> hashelemarray;
};
template<class T>
hashmap<T>::hashmap()
{
capcity = 20;
used = 0;
hashelemarray = vector<hashelem<T>>(capcity);
}
template<class T>
hashmap<T>::~hashmap()
{
hashelemarray.clear();
}
template<class T>
int hashmap<T>::cal_key_value(T elem)
{
// here we use only a simple way to calculate hash key
int largenum = 5;
return (elem%largenum);
}
template<class T>
void hashmap<T>::hashinsert(T elem)
{
if(used > 0.9 * capcity)
{
cout<<"The hashtable is too crowded!!! Please rebuild hashtable!"<<endl;
return;
}
int hashkey = cal_key_value(elem);
hashelemarray[hashkey].valuearray.push_back(elem);
hashelemarray[hashkey].key = hashkey;
used++;
}
template<class T>
void hashmap<T>::hashdelete(T elem)
{
int hashkey = cal_key_value(elem);
if(hashkey > hashelemarray.size())
{
cout << "ERROR:: NOT FIND"<<endl;
return;
}
vector<T> tmparray = hashelemarray[hashkey].valuearray;
int i;
bool find = false;
for(i = 0; i < tmparray.size();i++)
{
if(tmparray[i] == elem)
{
find = true;
break;
}
}
if(find)
{
tmparray.erase(tmparray.begin()+i);
if(tmparray.size() < 1)
{
hashelemarray[hashkey].key = -1;
hashelemarray[hashkey].valuearray = tmparray;
}
else
hashelemarray[hashkey].valuearray = tmparray;
used--;
}
else
{
cout<<"ERROR: NO such element in hash table!"<<endl;
return;
}
}
template<class T>
vector<hashelem<T>> hashmap<T>::buildhashtable(vector<T> elemarray)
{
vector<hashelem<T>> result;
if(elemarray.size() < 1)
return result;
for(int i =0; i < elemarray.size(); i++)
hashinsert(elemarray[i]);
return hashelemarray;
}
int main()
{
vector<int> V;
hashmap<int> HM;
for(int i = 0; i < 10; i++)
{
V.push_back(rand()%100);
}
HM.buildhashtable(V);
HM.hashdelete(V[3]);
system("pause");
return 0;
}