C 打印阵列

C++ printing array

本文关键字:阵列 打印      更新时间:2023-10-16

我正在研究C 中的线性和二次探测哈希表实现。在hash.cpp中,我有一个有效的线性prob(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 tablen";
           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;
           }
       }
   }
}

,我也有print()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();
    }
}

我可以看到我的探测有效,但请注意,我对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);
    }
}

但这仅在没有[i]的情况下打印出0〜9。当我测试一个[i]输入print()时,它给我所有的价值的[i]为-1,这会导致不打印任何东西。我真的很困惑为什么会发生这种情况。为什么print()即使在我通过main调用print()时起作用,也不会得到正确的[i]?

在您的"探针函数打印"中,您在函数中打印一个空的哈希h。您应该丢弃该Hash h;,然后致电print()而不是h.print()

这是一个不错的问题,调试器可以帮助您解决。在该分支中闯入时,它将显示一个空的h,而Main,h将被填充。