7 template<typename _Key, typename _Val>
11 struct hashlistnode<_Key,_Val> *next;
14 template<typename _Key, typename _Val, typename _KeyInt, int _Shift>
17 HashTable(unsigned int initialcapacity=1024, double factor=0.5) {
18 // Allocate space for the hash table
19 table = (struct hashlistnode<_Key,_Val> **) calloc(initialcapacity, sizeof(struct hashlistnode<_Key,_Val> *));
21 capacity = initialcapacity;
22 threshold = initialcapacity*loadfactor;
23 mask = (capacity << _Shift)-1;
24 size = 0; // Initial number of elements in the hash
28 for(unsigned int i=0;i<capacity;i++) {
29 struct hashlistnode<_Key,_Val> * bin = table[i];
31 struct hashlistnode<_Key,_Val> * next=bin->next;
40 for(int i=0;i<capacity;i++) {
41 struct hashlistnode<_Key,_Val> * bin = table[i];
43 struct hashlistnode<_Key,_Val> * next=bin->next;
48 memset(table, 0, capacity*sizeof(struct hashlistnode<_Key, _Val> *));
52 void put(_Key key, _Val val) {
53 if(size > threshold) {
55 unsigned int newsize = capacity << 1;
59 struct hashlistnode<_Key,_Val> *ptr = table[(((_KeyInt)key) & mask)>>_Shift];
61 struct hashlistnode<_Key,_Val> *search = ptr;
64 if (search->key==key) {
71 struct hashlistnode<_Key,_Val> *newptr=(struct hashlistnode<_Key,_Val> *)malloc(sizeof(struct hashlistnode<_Key,_Val>));
75 table[(((_KeyInt)key)&mask)>>_Shift]=newptr;
79 struct hashlistnode<_Key,_Val> *search = table[(((_KeyInt)key) & mask)>>_Shift];
82 if (search->key==key) {
90 bool contains(_Key key) {
91 struct hashlistnode<_Key,_Val> *search = table[(((_KeyInt)key) & mask)>>_Shift];
94 if (search->key==key) {
102 void resize(unsigned int newsize) {
103 struct hashlistnode<_Key,_Val> ** oldtable = table;
104 struct hashlistnode<_Key,_Val> ** newtable;
105 unsigned int oldcapacity = capacity;
107 if((newtable = (struct hashlistnode<_Key,_Val> **) calloc(newsize, sizeof(struct hashlistnode<_Key,_Val> *))) == NULL) {
108 printf("Calloc error %s %d\n", __FILE__, __LINE__);
112 table = newtable; //Update the global hashtable upon resize()
114 threshold = newsize * loadfactor;
115 mask = (newsize << _Shift)-1;
117 for(unsigned int i = 0; i < oldcapacity; i++) {
118 struct hashlistnode<_Key, _Val> * bin = oldtable[i];
122 struct hashlistnode<_Key, _Val> * next=bin->next;
124 unsigned int index = (((_KeyInt)key) & mask) >>_Shift;
125 struct hashlistnode<_Key, _Val> * tmp=newtable[index];
132 free(oldtable); //Free the memory of the old hash table
136 struct hashlistnode<_Key,_Val> **table;
137 unsigned int capacity;
140 unsigned int threshold;