Basic HashMap in C++

Useful Points

  1. I use chaining for key collisions.
  2. The key is also stored with the payload.
  3. A GET operation searches the key in bucket’s linked-list and returns the value.

using namespace std;

class HashNode {
    string key;
    string value;
    HashNode *next;

    HashNode(string key, string value) {
        this->key = key;
        this->value = value;
        this->next = NULL;

    string getValue() {
        return value;

class HashKey {
    long hash(string key) {
        return 100 + key[0];

class HashMap {
    size_t size;
    HashNode **table;
    HashKey hk;

    HashMap(size_t size) {
        table = new HashNode*[size];

    ~HashMap() {
            delete [] table;

    string get(string key) {
        long hash = hk.hash(key);
        HashNode *h = table[hash];
        return h->getValue();

    void put(string key, string value)
        long hash = hk.hash(key);
        table[hash] = new HashNode(key, value);

int main()
    HashMap *hm = new HashMap(1024);
    hm->put("mykey", "avalue");
    cout << hm->get("mykey") << endl;

    return 0; 


$ g++ ./
$ ./a.out

Leave a Reply

Please log in using one of these methods to post your comment: Logo

You are commenting using your account. Log Out /  Change )

Google photo

You are commenting using your Google account. Log Out /  Change )

Twitter picture

You are commenting using your Twitter account. Log Out /  Change )

Facebook photo

You are commenting using your Facebook account. Log Out /  Change )

Connecting to %s

This site uses Akismet to reduce spam. Learn how your comment data is processed.

%d bloggers like this: