AntInLoop

Hash Table (Hash Map) Code Implementations

Production-ready Hash Table (Hash Map) data structure implementations in C++, Python, Java, and JavaScript on AntInLoop.

Study Hash Table (Hash Map) Guide ยท Launch Visualizer

CPP Implementation

#include <vector>
#include <list>
#include <algorithm>

// Hash Table Class
class HashTable {
private:
    // Vector of lists to store the keys
    std::vector<std::list<int>> table;
    // Size of the table
    int total_elements;

    // Hash function to calculate hash for a value
    int compute_hash(int key) {
        return key % total_elements;
    }
public:
    // Constructor
    HashTable(int size) : total_elements(size) {
        table.resize(size);
    }

    // Insert a key into the hash table
    void insert(int key) {
        int hash_value = compute_hash(key);
        table[hash_value].push_back(key);
    }

    // Remove a key from the hash table
    void remove(int key) {
        int hash_value = compute_hash(key);
        table[hash_value].remove(key);
    }

    // Search for a key in the hash table
    bool search(int key) {
        int hash_value = compute_hash(key);
        return std::find(table[hash_value].begin(), table[hash_value].end(), key) != table[hash_value].end();
    }

    // Check if hash table is empty
    bool isEmpty() {
        for(auto &list: table)
            if(!list.empty())
                return false;
        return true;
    }

    // Get size of the hash table
    int size() {
        return total_elements;
    }
};