* @tparam _free Provide your own 'free' for the table, or default to
* snapshotting.
*/
-template<typename _Key, typename _Val, typename _KeyInt, int _Shift = 0, void * (* _malloc)(size_t) = snapshot_malloc, void * (* _calloc)(size_t, size_t) = snapshot_calloc, void (*_free)(void *) = snapshot_free, unsigned int (*hash_function)(_Key) = default_hash_function<_Key, _Shift, _KeyInt>, bool (*equals)(_Key, _Key) = default_equals<_Key> >
+template<typename _Key, typename _Val, typename _KeyInt, int _Shift = 0, void * (*_malloc)(size_t) = snapshot_malloc, void * (*_calloc)(size_t, size_t) = snapshot_calloc, void (*_free)(void *) = snapshot_free, unsigned int (*hash_function)(_Key) = default_hash_function<_Key, _Shift, _KeyInt>, bool (*equals)(_Key, _Key) = default_equals<_Key> >
class HashTable {
public:
/**
capacitymask = initialcapacity - 1;
threshold = (unsigned int)(initialcapacity * loadfactor);
- size = 0; // Initial number of elements in the hash
+ size = 0; // Initial number of elements in the hash
}
/** @brief Hash table destructor */
resize(capacity << 1);
struct hashlistnode<_Key, _Val> *search;
+ struct hashlistnode<_Key, _Val> *first = NULL;
- unsigned int index = hash_function(key);
+ unsigned int index = hash_function(key) & capacitymask;
+ unsigned int oindex = index;
do {
- index &= capacitymask;
search = &table[index];
if (!search->key) {
//key is null, probably done
- break;
+ if (!search->val)
+ break;
+ if (first == NULL)
+ first = search;
}
if (equals(search->key, key)) {
search->val = val;
return;
}
- index++;
+ index = (index + 1) & capacitymask;
+ if (index == oindex) {
+ if (first == NULL)
+ exit(-1);
+ break;
+ }
} while (true);
- search->key = key;
- search->val = val;
+ if (first != NULL) {
+ first->key = key;
+ first->val = val;
+ } else {
+ search->key = key;
+ search->val = val;
+ }
size++;
}
}
unsigned int oindex = hash_function(key) & capacitymask;
- unsigned int index=oindex;
+ unsigned int index = oindex;
do {
search = &table[index];
if (!search->key) {
return size;
}
+ bool isEmpty() {
+ return size == 0;
+ }
/**
* @brief Check whether the table contains a value for the given key
exit(EXIT_FAILURE);
}
- table = newtable; // Update the global hashtable upon resize()
+ table = newtable; // Update the global hashtable upon resize()
capacity = newsize;
capacitymask = newsize - 1;
search->val = bin->val;
}
- _free(oldtable); // Free the memory of the old hash table
+ _free(oldtable); // Free the memory of the old hash table
}
double getLoadFactor() {return loadfactor;}
unsigned int getCapacity() {return capacity;}
double loadfactor;
};
-#endif/* __HASHTABLE_H__ */
+#endif /* __HASHTABLE_H__ */