HashMap.h 1.8 KB

12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152535455565758596061626364656667686970717273747576777879808182838485868788
  1. #ifndef HASHMAP_H
  2. #define HASHMAP_H
  3. #include "utils/Array.h"
  4. template<typename K, typename V, int N_MIN>
  5. class HashMap {
  6. static constexpr int getCapacity() {
  7. int i = 1;
  8. while(i < N_MIN) {
  9. i <<= 1;
  10. }
  11. return i;
  12. }
  13. static constexpr int CAPACITY = getCapacity();
  14. static constexpr int MASK = CAPACITY - 1;
  15. Array<bool, CAPACITY> used;
  16. Array<K, CAPACITY> keys;
  17. Array<V, CAPACITY> values;
  18. int searchIndex(const K& key) const {
  19. int base = hash(key);
  20. for(int i = 0; i < CAPACITY; i++) {
  21. int h = (base + i) & MASK;
  22. if(!used[h]) {
  23. return -1;
  24. } else if(keys[h] == key) {
  25. return h;
  26. }
  27. }
  28. return -1;
  29. }
  30. public:
  31. HashMap() : used(false) {
  32. }
  33. void add(const K& key, const V& value) {
  34. int base = hash(key);
  35. for(int i = 0; i < CAPACITY; i++) {
  36. int h = (base + i) & MASK;
  37. if(!used[h]) {
  38. used[h] = true;
  39. keys[h] = key;
  40. values[h] = value;
  41. return;
  42. } else if(keys[h] == key) {
  43. values[h] = value;
  44. return;
  45. }
  46. }
  47. }
  48. const V& search(const K& key, const V& notFound) const {
  49. int index = searchIndex(key);
  50. return index == -1 ? notFound : values[index];
  51. }
  52. V& search(const K& key, V& notFound) {
  53. int index = searchIndex(key);
  54. return index == -1 ? notFound : values[index];
  55. }
  56. bool contains(const K& key) const {
  57. return searchIndex(key) != -1;
  58. }
  59. void clear() {
  60. used.fill(false);
  61. }
  62. private:
  63. template<typename H>
  64. static int hash(const H& key) {
  65. return key.hashCode();
  66. }
  67. static int hash(int key) {
  68. return key;
  69. }
  70. };
  71. #endif