shushus

Спринт 10. Искусство хеш-функций. Задание 1.

Mar 8th, 2023
549
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
C++ 1.31 KB | None | 0 0
  1. #include <iostream>
  2. #include <string>
  3. #include <unordered_map>
  4. #include <unordered_set>
  5. #include <sstream>
  6.  
  7. using namespace std;
  8.  
  9. template <typename Hash>
  10. int FindCollisions(const Hash& hasher, istream& text) {
  11.     string str;
  12.     int collisions = 0;
  13.    
  14.     unordered_map<size_t, unordered_set<string>> coll_hash;
  15.    
  16.     while(text >> str) {
  17.         const auto hash_ = hasher(str);
  18.        
  19.         if (const auto helper = coll_hash.find(hash_);
  20.             helper != coll_hash.end()) {
  21.            
  22.             collisions += helper->second.insert(str).second;
  23.            
  24.         } else {
  25.             coll_hash[hash_].insert(str);
  26.         }
  27.     }
  28.     return collisions;
  29. }
  30.  
  31. struct HasherDummy {
  32.     size_t operator() (const string& str) const {
  33.         size_t res = 0;
  34.         for (char c : str) {
  35.             res += static_cast<size_t>(c);
  36.         }
  37.         return res;
  38.     }
  39. };
  40.  
  41. struct DummyHash {
  42.     size_t operator()(const string&) const {
  43.         return 42;
  44.     }
  45. };
  46.  
  47. int main() {
  48.     DummyHash dummy_hash;
  49.     hash<string> good_hash;
  50.  
  51.     {
  52.         istringstream stream("I love C++"s);
  53.         cout << FindCollisions(dummy_hash, stream) << endl;
  54.     }
  55.     {
  56.         istringstream stream("I love C++"s);
  57.         cout << FindCollisions(good_hash, stream) << endl;
  58.     }
  59. }
Advertisement
Add Comment
Please, Sign In to add comment