在哈希表中搜索帮助

Searching in a hash table HELP!

本文关键字:帮助 搜索 哈希表      更新时间:2023-10-16

我正在尝试为类编写一个哈希表,但在循环工作时似乎无法得到它。 你们觉得有什么问题吗?while 循环过早结束,我认为我的 while 循环条件有问题?

void search(store t[], string s, int num, int table_size)
{
  int temp = num;
  bool exit = false;
  while(t[temp].data != s && !exit){
    temp++;
    if (temp == table_size){
      cout<<"reached 0 inside while loop"<<endl;
        temp = 0;
    }
    if (temp == num){
      cout<<"test search loop"<<endl;          //I can't seem to get into here.
      exit = true;
    }
  }
  if(t[num].data == s)
    cout<<"("<<s<<")"<<" appears "<<t[num].count<<" times."<<endl;
  else
    cout<<"your string is not in my table"<<endl;
}

你的while循环似乎还可以,

但是您确定以下行吗?

if(t[num].data == s)
    cout<<"("<<s<<")"<<" appears "<<t[num].count<<" times."<<endl;

不应该是以下的吗?

if(t[temp].data == s)
    cout<<"("<<s<<")"<<" appears "<<t[temp].count<<" times."<<endl;

因为很明显,您正在运行整个表,直到循环完成或直到找到好的 [ 即:while( t[temp].data != s ...) ]。所以我猜你正在寻找好的临时索引,但你没有在循环后使用它。

尝试更改

 int temp = num;

 int temp = 0;