我正在研究C++中的線性和二次探測哈希表實現。在Hash.cpp中,我有一個可用的linearProb(int key)和quadProb函數。如果我通過main.hpp單獨調用它們,它會打印出正確的散列表,但是我想在編譯時看到線性表和二次表的結果。C++打印陣列
這是我linearProb(quadProb比較相似)
void Hash::linearProb(int key){
int i, count = 0;
Hash h;
//if it is empty, place it there
if (a[key % tableSize] == -1)
a[key % tableSize] = key;
else{
i = 0;
//until finding an empty slot, but don't loop around
while (i < tableSize && a[i] != -1){
count++;
i++;
}
if(count == tableSize){
cout<<key<<" could not be inserted in the table\n";
exit(1);
}
//when there's a collision increase i by 1 until finding empty slot
for(i = (key % tableSize+1) % tableSize; i <tableSize; i++){
if(a[i] == -1){
a[i] = key;
break;
}
}
}
}
我也有印刷()在Hash.cpp
void Hash::print(){
int i;
//cout<<"Hash Table with Linear Probing"<<endl;
cout<<"\n Result Hash Table: "<<endl;
for(i = 0; i < tableSize; i++){
cout<<"\n"<<i;
if(a[i] != -1){
cout<<" "<< a[i];
}
}
cout<<"\n";
}
如果我把它在main.cpp中這樣
int main(){
int key;
Hash h;
//take in .txt file
std::fstream file;
file.open("keys.txt");
while(!file.eof()){
file >> key;
if(key != -1){
h.linearProb(key);
//h.quadProb(key);
}
}
file.close();
if(key == -1){
h.print();
}
}
我可以看到我的探測工作,但注意到我爲了測試linearProb而註釋掉了quadProb。我想同時打印兩張表。爲了做到這一點,我試圖在每個探測函數中調用print(),而不是從main調用它。
這就是我試過的。我改變主()來
while(!file.eof()){
file >> key;
h.linearProb(key);
//h.quadProb(key);
}
file.close();
,並加入到linearProb(INT鍵)
void Hash::linearProb(int key){
int i, count = 0;
Hash h;
if(key == -1){
h.print();
exit(1);
}
}
但這僅打印出0〜9無[i]中。當我測試[i]是什麼時它進入print(),並且它給了我所有我值爲[i] -1,這導致不打印任何東西。我很困惑爲什麼會這樣。爲什麼print()不正確a [i],即使它在我通過main調用print()時工作?
閱讀你的代碼我有點困惑,你能否提供一個[最小化,完整和可驗證的例子](http://stackoverflow.com/help/mcve)? – Steeve
插入代碼時:插入格式化代碼,選擇所有內容並按{}圖標(代碼示例) – stefaanv