【问题标题】:Hash Tables: why doesn't this code resolve collisions?哈希表:为什么这段代码不能解决冲突?
【发布时间】:2014-06-05 16:07:34
【问题描述】:

这个插入函数似乎没有正确插入并覆盖以前的条目。此外,重复检查也不能按预期工作,只能工作一半。

HT::HT(const unsigned& tblSize) {

  //Hash table size equal to size passed or default size TBL_SIZE
  hsize = tblSize;
  //Pointer table defualt 0
  psize = 0;

  //reisze tables
  hTable.resize(hsize);
  pTable.resize(hsize);

  //set unused values to empty($$$)
  for(unsigned i = 0; i < hsize; i++)
    hTable[i].key = FREE;
}


//implementation of insert function
void HT::insert(const Entry& record) {

  //assign integer value to index via hash function
  int index = (hash(record.key) % 31);

  //logic to insert into hash table
  for(unsigned i = 0; i < hsize; i++) {
    //inserting into table with linear probing collision resolution

    //inserting into hash table with linear probing as collision resolution
    if (hTable[(index+i)%hsize].key == FREE) {

      hTable[index] = record;
      pTable[psize] = &hTable[(index+i)%hsize];
      psize++;
      cout << " Entry = " << ((index+i)%hsize) << endl;

      return;
    }

    //Duplicate key check
    else if (hTable[(index+i)%hsize].key == record.key) {
      cout << " Entry = Not Inserted - Duplicate key!! " << endl; return;
    }

    //Capacity of table check
    else if (i == hsize - 1) {
      cout << " Not Inserted -  Table full!! " << endl; return;
    }

  } //end for loop
}

似乎插入得很好,重复键检查适用于一个数据集,但不适用于另一个数据集,有更多数据值将表填充为 TBL_SIZE = 31。此外,FREE 常量将所有向量值设置为 $$$ 以指定一个空位。

【问题讨论】:

    标签: c++ vector hashmap hashtable hash-collision


    【解决方案1】:
    //inserting into hash table with linear probing as collision resolution
    if (hTable[(index+i)%hsize].key == FREE) {
    
      hTable[index] = record;
    

    当 [(index + i)%hsize] 是空闲位置时,您不想插入到 [index] 中。

    【讨论】:

    • 这是一个不错的收获!
    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2015-07-25
    • 1970-01-01
    • 1970-01-01
    • 2019-10-01
    • 2011-06-06
    相关资源
    最近更新 更多