C 打印阵列
C++ printing array
我正在研究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
将被填充。
相关文章:
- 库特<<恩德尔;不适用于打印 2D 阵列
- 数组类 阵列的打印输出
- 阵列打印功能
- 打印原始阵列和更改的阵列
- 多次打印出整个阵列
- 无法弄清楚为什么我的打印阵列要替换元素
- 阵列无法正确打印 C++
- 如何打印一个字符阵列和其中的特定字符
- C++ Visual 工作室中的逻辑错误.阵列打印的是地址而不是内容
- 指针阵列打印值
- 打印我的字符串阵列时,会遇到细分错误
- 从指针打印动态int阵列中获取怪异的字符
- 无法打印阵列或分配给阵列
- 有没有办法更快地打印2D阵列
- 为什么 2-D 阵列在不应该打印的地方打印 1?
- 如何打印char阵列的地址
- 如何从FIFO队列阵列打印
- 双面2D阵列打印
- 使用1d阵列打印2d阵列
- 阵列打印Segfault