Advertisement
ShadyLiar

HashTable

Apr 18th, 2024
686
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
C++ 0.90 KB | None | 0 0
  1. #include <iostream>
  2. #include <string>
  3.  
  4. const int TABLE_SIZE = 100;
  5.  
  6. int hashFunction(const std::string& key) {
  7.     int hashValue = 0;
  8.     for (char ch : key) {
  9.         hashValue = (hashValue * 29 + ch) % TABLE_SIZE;
  10.     }
  11.     return hashValue;
  12. }
  13.  
  14. struct Pair {
  15.     std::string key;
  16. };
  17. class HashTable {
  18. private:
  19.     Pair table[TABLE_SIZE];
  20.  
  21. public:
  22.     void insert(const std::string& key) {
  23.         int index = hashFunction(key);
  24.         while (!table[index].key.empty()) {
  25.             index = (index + 1) % TABLE_SIZE;
  26.         }
  27.         table[index].key = key;
  28.     }
  29.     bool search(const std::string& key) {
  30.         int index = hashFunction(key);
  31.         while (!table[index].key.empty()) {
  32.             if (table[index].key == key) //
  33.                 return true;
  34.             index = (index + 1) % TABLE_SIZE; //
  35.         }
  36.         return false;
  37.     }
  38. };
  39.  
  40. int main() {
  41.     return 0;
  42. }
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement