我用 C++ 编写了一个使用线性探测进行散列的程序。代码在编译时没有显示错误,但是当我运行它时,计算机显示程序已停止工作的通知。我在下面给出整个代码。请帮帮我。
#include<iostream>
#include<vector>
using namespace std;
class Acc
{
public:
int iData;
double dData;
Acc(int id,double dd)
{
iData = id;
dData = dd;
}
void displayAcc()
{
cout<<"iData = "<<iData<<"\n";
cout<<"dData = "<<dData<<"\n";
}
};
class Linear_Hash
{
private:
vector<Acc*> hashArray;
int nElem;
Acc* noElem;
public:
Linear_Hash(int max)
{
nElem = max;
hashArray.resize(nElem);
noElem = new Acc(-1,1.1);
for(int i = 0;i<max;i++)
{
hashArray[i] = NULL;
}
}
int hashfunc(int key)
{
return key%nElem;
}
void insertAcc(int id,double dd)
{
Acc* newacc = new Acc(id,dd);
int hashVal = hashfunc(id);
while(hashArray[hashVal]->iData!=-1&&hashArray[hashVal]!=NULL)
{
hashVal++;
hashVal = hashVal%nElem;
}
hashArray[hashVal] = newacc;
}
Acc* search(int key)
{
int hashVal = key%nElem;
while(hashArray[hashVal]->iData!=key&&hashArray[hashVal]!=NULL)
{
hashVal++;
hashVal = hashVal%nElem;
}
if(hashArray[hashVal]->iData==key)
{
return hashArray[hashVal];
}
else
return NULL;
}
bool deleteAcc(int key)
{
int hashVal = hashfunc(key);
while(hashArray[hashVal]->iData!=key&&hashArray[hashVal]!=NULL)
{
hashVal++;
hashVal = hashVal%nElem;
}
if(hashArray[hashVal]==NULL)
return false;
else
{
Acc* pTemp = hashArray[hashVal];
hashArray[hashVal] = noElem;
delete pTemp;
return true;
}
}
};
int main(void)
{
int key;
char val;
Linear_Hash lh(20);
lh.insertAcc(100,100.1);
lh.insertAcc(204,204.204);
lh.insertAcc(105,105.10);
lh.insertAcc(237,348.23);
lh.insertAcc(209,923.23);
lh.insertAcc(230,230.23);
lh.insertAcc(403,348.34);
lh.insertAcc(405,938.50);
lh.insertAcc(450,348.23);
lh.insertAcc(945,495.409);
while(val!='x')
{
cout<<"Enter the key to be searched\n";
cin>>key;
if(lh.search(key)==NULL)
cout<<key<<" could not be found\n";
else
lh.search(key)->displayAcc();
cout<<"Enter the key to be deleted\n";
cin>>key;
if(lh.deleteAcc(key))
cout<<key<<" has been deleted\n";
else
cout<<"Invalid request\n";
cout<<"Do you want to continue\n";
cin>>val;
}
return 0;
}
在这种情况下,我无法使用调试器,因为我不知道错误在哪里。我也尝试在纸上空运行它,但无法确定错误。