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.
#include<bits/stdc++.h>

using namespace std;

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

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

    string getValue() {
        return value;
    }
};

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

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

    public:
    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; 
}

Execution

$ g++ ./hashmap.cc
$ ./a.out
avalue

Leave a Reply

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

WordPress.com Logo

You are commenting using your WordPress.com 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.