example1_conceptual_hash_table.cpp

 1
 2
 3
 4
 5
 6
 7
 8
 9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
#include <iostream>
#include <vector>
#include <list>
#include <string>

// Simple hash function
int hashFunction(const std::string& key, int tableSize) {
    int hashValue = 0;
    for (char ch : key) {
        hashValue += ch;
    }
    return hashValue % tableSize;
}

class HashTable {
public:
    HashTable(int size) : table(size) {}

    void insert(const std::string& key, int value) {
        int hashValue = hashFunction(key, table.size());
        table[hashValue].emplace_back(key, value);
    }

    bool lookup(const std::string& key, int& value) {
        int hashValue = hashFunction(key, table.size());
        for (auto& [k, v] : table[hashValue]) {
            if (k == key) {
                value = v;
                return true;
            }
        }
        return false;
    }

    void remove(const std::string& key) {
        int hashValue = hashFunction(key, table.size());
        table[hashValue].remove_if([&](const std::pair<std::string, int>& item) {
            return item.first == key;
        });
    }

private:
    std::vector<std::list<std::pair<std::string, int>>> table;
};

int main() {
    HashTable ht(10);

    // Insert key-value pairs
    ht.insert("apple", 100);
    ht.insert("banana", 150);
    ht.insert("orange", 200);

    // Lookup values
    int value;
    if (ht.lookup("banana", value)) {
        std::cout << "Value for 'banana': " << value << std::endl;
    } else {
        std::cout << "'banana' not found." << std::endl;
    }

    // Remove a key-value pair
    ht.remove("banana");
    if (ht.lookup("banana", value)) {
        std::cout << "Value for 'banana': " << value << std::endl;
    } else {
        std::cout << "'banana' not found." << std::endl;
    }

    return 0;
}
Back to hash_table