c++ - 哈希示例 - 多余的代码

标签 c++

我找到了这段代码 here作为最简单的哈希类型的示例。它有点使因为..基本上使用模数运算符将数据集从 DATA_SIZE(隐含)减少到 TABLE_SIZE(定义)。

但是,如果发生冲突,即数组元素已经被占用,则移动到

hash = (hash + 1) % TABLE_SIZE

但是,如果您已经使用 TABLE SIZE 进行了取模,则此行将始终生成 (hash+1) b.c。当 x < y 时,x % y 总是等于 x。问题:这是一个错误吗……我的意思是它应该可以工作,但是 % TABLE_SIZE 是额外的,对吗?它在下面的代码中什么都不做。

const int TABLE_SIZE = 128;

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;
      }
  }; 

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;
      }
  };

最佳答案

该模数在溢出的情况下存在。

假设 hash == TABLE_SIZE - 1。然后 hash + 1 == TABLE_SIZE,而 hash+1 % TABLE_SIZE == 0

关于c++ - 哈希示例 - 多余的代码,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/7771285/

相关文章:

c++ - 无法将流代码与 gcc 链接

c++ - IPersistFile 加载未定义的返回值

c++ - 使用 SimpleJSON 库 (C++) 的多个定义

c++ - 使用 Qt Creator 调整 .ui 文件如何导致编译期间更改 .h 文件?

c++ - 一个循环内的多次递归调用是如何展开的?

简单场景的 C++ OO 继承正确性

c++ - 如何痛饮省略前向声明

c++ - 在没有条件的情况下将一个 unsigned char 的一位设置为另一个 unsigned char 的另一位

c++ - Visual Studio 2008调试;在写入值时中断

c++ - 找不到强制包含的 header