Untitled
#include <iostream> #include <list> #include <string> using namespace std; class SymbolTable { private: static const int TABLE_SIZE = 10; list<pair<string, int>> table[TABLE_SIZE]; int hashFunction(string key) { int hash = 0; for (char ch : key) { hash += ch; } return hash % TABLE_SIZE; } public: void insert(string key, int value) { int index = hashFunction(key); for (auto& entry : table[index]) { if (entry.first == key) { entry.second = value; // Update value if key already exists return; } } table[index].emplace_back(key, value); } int lookup(string key) { int index = hashFunction(key); for (auto& entry : table[index]) { if (entry.first == key) { return entry.second; } } return -1; // Return -1 if the key is not found } void remove(string key) { int index = hashFunction(key); for (auto it = table[index].begin(); it != table[index].end(); ++it) { if (it->first == key) { table[index].erase(it); return; } } } void display() { for (int i = 0; i < TABLE_SIZE; i++) { cout << "Index " << i << ": "; for (auto& entry : table[i]) { cout << "[" << entry.first << ": " << entry.second << "] "; } cout << endl; } } }; int main() { SymbolTable st; // Insert symbols st.insert("x", 10); st.insert("y", 20); st.insert("z", 30); // Lookup symbols cout << "Lookup 'x': " << st.lookup("x") << endl; // Output: 10 cout << "Lookup 'y': " << st.lookup("y") << endl; // Output: 20 // Delete a symbol st.remove("y"); cout << "Lookup 'y' after deletion: " << st.lookup("y") << endl; // Output: -1 // Display the symbol table st.display(); return 0; }
Leave a Comment