霍夫曼解码中的递归函数不退出
Recursive function in Huffman Decoding not exiting
我在创建霍夫曼解码功能时遇到了一些麻烦。我只是想知道是否有人知道为什么我的程序会产生无限循环。下面是我的函数以及我是如何计算它的。当计数器命中 8 时,它应该退出函数,因为没有更多的位要读取。在这里:
HuffmanNode *rodee = createTree(freqArray2, 256); //holds the huffman tree
HuffmanNode *temporaryNode; //temporary node for traversing
temporaryNode = rodee; //first the temporary node is equal to the root
while(cin.read((char*)&w, sizeof(w))
{
traverseCode(temporaryNode, rodee, bits, count);
count = 0; //reset the count back to 0 for the next time the function is called
} //as I read in a byte of 8 bits (I converted the bytes to bits in another function not shown
void traverseCode(HuffmanNode *temp, HuffmanNode *root, unsigned char *bits, int counter)
{
if(counter >= 7)
{
counter = 0;
return;
}
if(temp->getLeft() == NULL && temp->getRight() == NULL)
{
cout << temp->getLetter();
temp = root;
traverseCode(temp, root, bits, counter);
}
if((int)bits[counter] == 0)
{
traverseCode(temp->getLeft(), root, bits, counter++);
}
if((int)bits[counter] == 1)
{
traverseCode(temp->getRight(), root, bits, counter++);
}
}
有谁知道为什么我的函数会进入无限循环以及如何解决这个问题?谢谢!
如果您希望计数器由 traverseCode() 函数更新,它需要是一个引用或指针。在您的代码中,它只是一个局部变量,在函数退出时被丢弃。
所以这什么也没做,除了返回:
if(counter >= 7)
{
counter = 0;
return;
}
接下来的一点也令人困惑。它将调用具有原始值"counter"的函数,这很可能是无限循环的来源。如果它确实返回,它将增加计数器的本地值,然后下降到下一个 if(),这也可能是无意的。
if((int)bits[counter] == 0)
{
traverseCode(temp->getLeft(), root, bits, counter++);
}
if((int)bits[counter] == 1)
{
traverseCode(temp->getRight(), root, bits, counter++);
}
因此,您可能需要以完全不同的方式处理计数器,并且不要让您的 if() 语句像那样失败。
相关文章:
- 递归函数计算序列中的平方和(并输出过程)
- 如何在Elixir中调用递归函数并行
- 递归函数有效,但无法记忆
- 为什么我的递归函数按降序打印,然后按升序打印?
- 为什么递归函数的最终输出是 5?
- 有没有办法使用递归函数找到数组中最小值的 INDEX?C++
- 如何将记忆应用于此递归函数?
- 如何从递归函数中完全返回,该函数给出了每个函数结果的累积相加?
- 无穷大而循环时具有递归函数
- 即使没有调用这个递归函数,它是如何工作的?
- 如何使此递归函数从给定的起始位置返回最小的整数?
- 此递归函数的每次迭代的值存储在哪里?
- 可以清除递归函数中的变量吗?
- 如何在递归函数调用中返回当前函数值
- 递归函数 c++ 的复杂性
- 这个递归函数有什么作用?运行时的复杂性是多少?
- 任何人都可以查明我的递归函数中的错误吗?
- C++ 调试递归函数,它不会立即退出函数
- 满足动态条件时退出递归函数
- 霍夫曼解码中的递归函数不退出