Implement a hash table in C ++

The following is a hash table implementation using C ++. Could you help me understand what is HashEntry **table? Why is it declared as a double pointer? Is it an array and every value of the array HashEntry?

  class HashEntry {
    private:
          int key;
          int value;
    public:
          HashEntry(int key, int value) {
                this->key = key;
                this->value = value;
          }

          int getKey() {
                return key;
          }

          int getValue() {
                return value;
          }
    };

    const int TABLE_SIZE = 128;






    class HashMap {
    private:
          HashEntry **table;
    public:
          HashMap() {
                table = new HashEntry*[TABLE_SIZE];
                for (int i = 0; i < TABLE_SIZE; i++)
                      table[i] = NULL;
          }

          int get(int key) {
                int hash = (key % TABLE_SIZE);
                while (table[hash] != NULL && table[hash]->getKey() != key)
                      hash = (hash + 1) % TABLE_SIZE;
                if (table[hash] == NULL)
                      return -1;
                else
                      return table[hash]->getValue();
          }

          void put(int key, int value) {
                int hash = (key % TABLE_SIZE);
                while (table[hash] != NULL && table[hash]->getKey() != key)
                      hash = (hash + 1) % TABLE_SIZE;
                if (table[hash] != NULL)
                      delete table[hash];
                table[hash] = new HashEntry(key, value);
          }     

          ~HashMap() {
                for (int i = 0; i < TABLE_SIZE; i++)
                      if (table[i] != NULL)
                            delete table[i];
                delete[] table;
          }
    };
+4
source share
1 answer

In this code tableis a pointer to a pointer to a HashEntry

HashEntry **table;

The general rule is to start with the name of the variable and the main type, turn right as much as possible, then go left, see this great description

http://unixwiz.net/techtips/reading-cdecl.html

, table HashEntry, . , "C", struct, ++ HashEntry "C".

table is ... HashEntry

table, , "*", :

table is pointer to ... HashEntry

"*",

table is pointer to pointer to HashEntry

... .

, , table , , . , ++, C, "" , . "" , , .

, , , :

HashEntry * table[];

, ,

table is undimensioned array of pointer to HashEntry

, ( 0), " " . . SO .

?

+4

Source: https://habr.com/ru/post/1660026/


All Articles