Guest User

Hash Map?

a guest
May 2nd, 2016
133
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
C++ 1.09 KB | None | 0 0
  1.  
  2. template <typename T>
  3. class HashTable
  4. {
  5. public:
  6.     HashTable(int amount)
  7.     {
  8.         size = amount;
  9.         values = new T*[size];
  10.         for (int i = 0; i < size; i++)
  11.         {
  12.             *(values + i) = nullptr;
  13.         }
  14.     }
  15.     ~HashTable()
  16.     {
  17.         if(values != nullptr)
  18.         {
  19.             for (int i = 0; i < size; i++)
  20.             {
  21.                 if(*(values + i) != nullptr)
  22.                 {
  23.                     delete *(values + i);
  24.                     *(values + i) = nullptr;
  25.                 }
  26.             }
  27.             delete[] values;
  28.         }
  29.     }
  30.  
  31.     int hash(const std::string & key)
  32.     {
  33.         int value = 0;
  34.         for (unsigned int i = 0; i < key.length(); i++)
  35.         {
  36.             value += key[i] * (i + 1);
  37.         }
  38.         return value % size;
  39.     }
  40.  
  41.     void addValue(const std::string & key, T value)
  42.     {
  43.         int location = hash(key);
  44.  
  45.         if (*(values + location) == nullptr)
  46.         {
  47.             *(values + location) = new T;
  48.         }
  49.  
  50.         **(values + location) = value;
  51.     }
  52.    
  53.     void printValues()
  54.     {
  55.         for (int i = 0; i < size; i++)
  56.         {
  57.             if (*(values + i) != nullptr)
  58.             {
  59.                 printf("value : %i\n", **(values + i));
  60.             }
  61.         }
  62.     }
  63.  
  64.     T* getValue(const std::string & key)
  65.     {
  66.         return *(values + hash(key))
  67.     }
  68.  
  69.     int size;
  70.     T ** values = nullptr;
  71. };
Advertisement
Add Comment
Please, Sign In to add comment