I'm working on linear and quadratic probing hash table implementation in C++. In Hash.cpp, I have a working linearProb(int key) and quadProb functions. If I call them separately through main.hpp, it prints out correct hash table, but I want to see the result of both linear and quadratic tables when I compile.
This is my linearProb (quadProb looks similar)
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;
}
}
}
}
and I also have print() in 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";
}
If I call it in main.cpp like this
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();
}
}
I can see that my probing works, but notice that I commented out quadProb in order to test linearProb. I want to print out both tables at the same time. In order to do that, I attempted to call print() in each probing function instead of calling it from main.
This is what I tried. I changed main() to
while(!file.eof()){
file >> key;
h.linearProb(key);
//h.quadProb(key);
}
file.close();
and added to linearProb(int key)
void Hash::linearProb(int key){
int i, count = 0;
Hash h;
if(key == -1){
h.print();
exit(1);
}
}
But this only print out 0~9 without a[i]. When I tested what a[i] is when it enters print(), and it gives me all i value has a[i] of -1, which leads to not printing out anything. I'm really confused why this is happening. Why is print() not getting correct a[i] even though it worked when I called print() through main?
In your "print from probe function", you print an empty hash h declared in the function. You should drop that Hash h;
and just call print()
instead of h.print()
.
This is a nice problem that a debugger can help you with. When breaking in that branch, it would show an empty h
, while in main, h
would be filled.
The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.