Skip to content

Instantly share code, notes, and snippets.

@jtomschroeder
Forked from aozturk/HashMap.h
Last active August 29, 2015 13:56
Show Gist options
  • Save jtomschroeder/8829938 to your computer and use it in GitHub Desktop.
Save jtomschroeder/8829938 to your computer and use it in GitHub Desktop.
#include <iostream>
#include <functional>
using namespace std;
template <typename K, typename V, int TABLE_SIZE = 100>
class HashMap
{
private:
struct HashNode
{
HashNode(K k, V v) : key(k), value(v) {}
K key;
V value;
HashNode *next = nullptr;
};
HashNode **table;
function<K (K)> hash_fn;
public:
HashMap(function<K (K)> F) : hash_fn(F)
{
// construct zero initialized hash table of size
table = new HashNode *[TABLE_SIZE]();
}
HashMap() : hash_fn([](K key) { return key % 100; })
{
// construct zero initialized hash table of size
table = new HashNode *[TABLE_SIZE]();
}
~HashMap()
{
// destroy all buckets one by one
for (int i = 0; i < TABLE_SIZE; ++i)
{
HashNode *entry = table[i];
while (entry != NULL)
{
HashNode *prev = entry;
entry = entry->next;
delete prev;
}
table[i] = NULL;
}
// destroy the hash table
delete [] table;
}
bool get(const K &key, V &value)
{
unsigned long hashValue = hash_fn(key);
HashNode *entry = table[hashValue];
while (entry != NULL)
{
if (entry->key == key)
{
value = entry->value;
return true;
}
entry = entry->next;
}
return false;
}
void put(const K &key, const V &value)
{
unsigned long hashValue = hash_fn(key);
HashNode *prev = NULL;
HashNode *entry = table[hashValue];
while (entry != NULL && entry->key != key)
{
prev = entry;
entry = entry->next;
}
if (entry == NULL)
{
entry = new HashNode(key, value);
if (prev == NULL)
{
// insert as first bucket
table[hashValue] = entry;
}
else
{
prev->next = entry;
}
}
else
{
// just update the value
entry->value = value;
}
}
void remove(const K &key)
{
unsigned long hashValue = F(key);
HashNode *prev = NULL;
HashNode *entry = table[hashValue];
while (entry != NULL && entry->key != key)
{
prev = entry;
entry = entry->next;
}
if (entry == NULL)
{
// key not found
return;
}
else
{
if (prev == NULL)
{
// remove first bucket of the list
table[hashValue] = entry->next;
}
else
{
prev->next = entry->next;
}
delete entry;
}
}
};
int main()
{
HashMap<int, int> h;
h.put(1, 10);
return 0;
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment