[英]C++ printing array
我正在研究C ++中的線性和二次探測哈希表實現。 在Hash.cpp中,我有一個有效的linearProb(int鍵)和quadProb函數。 如果我通過main.hpp分別調用它們,它將打印出正確的哈希表,但是我想在編譯時看到線性表和二次表的結果。
這是我的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中也有print()
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調用它。
這就是我嘗試過的。 我將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而沒有a [i]。 當我測試a [i]進入print()時是什么時,它給我的所有i值的a [i]均為-1,這導致不打印任何內容。 我真的很困惑為什么會這樣。 為什么當我通過main調用print()時,print()無法獲得正確的a [i]?
在“從探測函數打印”中,打印在函數中聲明的空哈希h。 您應該刪除該Hash h;
然后只需調用print()
而不是h.print()
。
這是一個很好的問題,調試器可以幫助您。 在該分支中中斷時,它將顯示一個空的h
,而在主分支中, h
將被填充。
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.