#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;
}