哈希表:为什么这段代码不能解决冲突?

时间:2014-04-21 15:04:14

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

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

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常量将所有向量值设置为$$$以指定a自由现场。

1 个答案:

答案 0 :(得分:0)

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

  hTable[index] = record;

当[(index + i)%hsize]为空闲位置时,您不希望插入[index]。