2016-12-02 127 views
-1

我正在研究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()时工作?

+0

阅读你的代码我有点困惑,你能否提供一个[最小化,完整和可验证的例子](http://stackoverflow.com/help/mcve)? – Steeve

+0

插入代码时:插入格式化代码,选择所有内容并按{}图标(代码示例) – stefaanv

回答

2

在“打印探测函数”中,打印函数中声明的空散列h。你应该放弃Hash h;,只需拨打print()而不是h.print()

这是一个很好的问题,调试器可以帮助你。当打破那个分支时,它将显示一个空的h,而在主体中,将填充h