Advertisement
smatskevich

HashTable

Dec 14th, 2023
833
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
C++ 1.27 KB | None | 0 0
  1. #include <algorithm>
  2. #include <iostream>
  3. #include <string>
  4. #include <vector>
  5.  
  6. using namespace std;
  7.  
  8. int Hash(const string& key) {
  9.   return key.empty() ? 0 : key.back();
  10. }
  11.  
  12. class HashTable {
  13.  public:
  14.   HashTable() : table_(8) {}
  15.   bool Add(const string& key) {
  16.     int h = Hash(key) % table_.size();
  17.     auto& v = table_[h];
  18.     auto it = find(v.begin(), v.end(), key);
  19.     if (it != v.end()) return false;
  20.     v.push_back(key);
  21.     return true;
  22.   }
  23.   bool Remove(const string& key) {
  24.     int h = Hash(key) % table_.size();
  25.     auto& v = table_[h];
  26.     auto it = find(v.begin(), v.end(), key);
  27.     if (it == v.end()) return false;
  28.     v.erase(it);
  29.     return true;
  30.   }
  31.   bool Has(const string& key) {
  32.     int h = Hash(key) % table_.size();
  33.     auto& v = table_[h];
  34.     auto it = find(v.begin(), v.end(), key);
  35.     return it != v.end();
  36.   }
  37.  
  38.  private:
  39.   vector<vector<string>> table_;
  40. };
  41.  
  42. int main() {
  43.   HashTable t;
  44.   string command, key;
  45.   while (cin >> command >> key) {
  46.     if (command == "+") {
  47.       cout << (t.Add(key) ? "OK" : "FAIL") << "\n";
  48.     } else if (command == "-") {
  49.       cout << (t.Remove(key) ? "OK" : "FAIL") << "\n";
  50.     } else if (command == "?") {
  51.       cout << (t.Has(key) ? "OK" : "FAIL") << "\n";
  52.     }
  53.   }
  54.   return 0;
  55. }
  56.  
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement