【问题标题】:Implement hash-table in C++在 C++ 中实现哈希表
【发布时间】:2017-03-20 06:53:33
【问题描述】:

以下是使用C++实现的hashtable。你能帮我理解HashEntry **table是什么吗?为什么它被声明为双指针?是不是一个数组,数组的每个值都是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;
          }
    };

【问题讨论】:

  • 仅用于面试问题。
  • @πάνταῥεῖ 你不是说std::unordered_map吗?
  • @user2899162 是的,std::unordered_map 实际上是哈希映射实现。
  • @Anni_housie HashEntry** 是一个动态二维数组
  • @Anni_housie 看看这个链接很有用:stackoverflow.com/questions/936687/…

标签: c++ hash hashmap hashtable


【解决方案1】:

在这段代码中,table 是一个指向 HashEntry 的指针

HashEntry **table;

一般规则是从变量名和基本类型开始,尽可能向右走,然后向左走,看这个精彩的描述

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

因此,您从变量table 和最左边的基本类型HashEntry 开始。请注意,本文描述了“C”的规则,其中基本类型可以是 struct,请将您的 C++ 类 HashEntry 视为“C”结构。

table is ... HashEntry

声明中table 右侧没有其他内容,所以向左走,你有“*”代表指向的指针

table is pointer to ... HashEntry

再一次,你必须在声明中向左走并消耗下一个“*”,你现在有

table is pointer to pointer to HashEntry

...你就完成了。

table 以这种方式声明可能是不幸的,因为 table 隐含数组,并且它没有被声明为数组。事实证明,在 C++ 中,与在 C 中一样,数组在传递给函数时“衰减”为指针。这里的“decays”意味着你丢失了信息,即数组的大小。

我认为可以让读者更深入地了解的等效声明是:

HashEntry * table[];

使用关于如何解释变量声明的规则,这应该被理解为

table is undimensioned array of pointer to HashEntry

从编译器的角度来看,这与前面的声明是等价的,因为 无尺寸数组 作为指向数组元素类型的指针(值是第一个元素,偏移量 0)。 “维数数组”也衰减为指针,丢失维数信息。有关数组衰减为指针的更多信息,请参阅此 SO 答案。

What is array decaying?

【讨论】:

    猜你喜欢
    • 2012-05-27
    • 2011-01-30
    • 1970-01-01
    • 2016-03-25
    • 2011-10-14
    • 2011-09-15
    • 2015-02-25
    相关资源
    最近更新 更多