我用C++編寫了一個程序,用於使用線性探測進行散列。代碼在編譯時沒有顯示錯誤,但是當我運行它時,計算機顯示程序已停止工作的通知。我在下面給出整個代碼。請幫助我。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;
}
我不能在這種情況下使用調試器,因爲我不知道錯誤在哪裏。我也嘗試在紙上幹運行它,但無法指出錯誤。
通知說什麼? – doctorlove
[不是崩潰的原因]這會泄漏內存:'noElem = new Acc(-1,1.1);'因爲你沒有在析構函數中刪除它。 –
@doctorlove: - 通知只是說程序已停止工作。它沒有提到墜機原因。我認爲一些超出範圍的數組訪問可能是原因。但我無法找到該訪問的根源。 – kusur