basic_hash.cc 1.1 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960
  1. #include "basic_hash.h"
  2. BasicHash::BasicHash(UInt64 size): array(new Bucket[size]), size(size)
  3. {
  4. }
  5. BasicHash::~BasicHash()
  6. {
  7. delete[] array;
  8. }
  9. std::pair<bool, UInt64> BasicHash::find(UInt64 key)
  10. {
  11. UInt64 index = key % size;
  12. Bucket& bucket = array[index];
  13. Bucket::iterator it = bucket.find(key);
  14. if (it == bucket.end())
  15. {
  16. // condition to assert no collision
  17. assert(bucket.size() == 0);
  18. return std::make_pair(false, ~0);
  19. }
  20. return std::make_pair(true, it->second);
  21. }
  22. bool BasicHash::insert(UInt64 key, UInt64 value)
  23. {
  24. UInt64 index = key % size;
  25. Bucket& bucket = array[index];
  26. std::pair<Bucket::iterator, bool> res = bucket.insert(std::make_pair(key, value));
  27. // condition to assert no collision
  28. assert(bucket.size() == 1);
  29. return res.second;
  30. }
  31. #ifdef DEBUG_BASIC_HASH
  32. int main(int argc, char* argv[])
  33. {
  34. BasicHash hash(100);
  35. UInt64 ids[4] = {1001, 1050, 1011, 1099};
  36. for (int i = 0; i < 4; i++)
  37. hash.insert(ids[i], i);
  38. for (int i = 3; i >= 0; i--)
  39. assert(hash.find(ids[i]).first == true);
  40. cerr << "All tests passed" << endl;
  41. return 0;
  42. }
  43. #endif