[英]Huffman Encoding C++ code is throwing a fatal error
我正在為著名的霍夫曼編碼算法編寫代碼。 我收到一個致命錯誤,將系統變成藍屏然后重新啟動。 此錯誤發生在具有遞歸調用的 display_Codes 中。 錯誤發生在以下幾行:
display_Codes(root->l, s + "0");
display_Codes(root->r, s + "1" );
以下是完整代碼。
#include <iostream>
#include <bits/stdc++.h>
using namespace std;
class HeapNode_Min {
public:
char d;
unsigned f;
HeapNode_Min *l, *r;
HeapNode_Min(char d, unsigned f)
{
this->d = d;
this->f = f;
}
~HeapNode_Min()
{
delete l;
delete r;
}
};
class Analyze {
public:
bool operator()(HeapNode_Min* l, HeapNode_Min* r)
{
return (l->f > r->f);
}
};
void display_Codes(HeapNode_Min* root, string s)
{
if(!root)
return;
if (root->d != '$')
cout << root->d << " : " << s << "\n";
display_Codes(root->l, s + "0");
display_Codes(root->r, s + "1" );
}
void HCodes(char data[], int freq[], int s)
{
HeapNode_Min *t,*r, *l ;
priority_queue<HeapNode_Min*, vector<HeapNode_Min*>, Analyze> H_min;
int a=0;
while (a<s){H_min.push(new HeapNode_Min(data[a], freq[a])); ++a;}
while (H_min.size() != 1) {
l = H_min.top(); H_min.pop();
r = H_min.top(); H_min.pop();
t = new HeapNode_Min('$', r->f + l->f);
t->r = r; t->l = l;
H_min.push(t);
}
display_Codes(H_min.top(), "");
}
int main()
{
try
{
int frequency[] = { 3, 6, 11, 14, 18, 25 }; char alphabet[] = { 'A', 'L', 'O', 'R', 'T', 'Y' };
int size_of = sizeof(alphabet) / sizeof(alphabet[0]);
cout<<"Alphabet"<<":"<<"Huffman Code\n";
cout<<"--------------------------------\n";
HCodes(alphabet, frequency, size_of);
}
catch(...)
{
}
return 0;
}
您從未將l
或r
設置為nullptr
,但您的代碼依賴於有效或nullptr
的指針:
void display_Codes(HeapNode_Min* root, string s) { if(!root) return; if (root->d != '$') cout << root->d << " : " << s << "\\n"; display_Codes(root->l, s + "0"); display_Codes(root->r, s + "1" ); }
傳遞一個root
,沒有左,無權節點,則既不root->l
,也沒有root->r
有一個值,你可以用任何東西。 將它們傳遞給下一個遞歸可以讓您取消引用它們,從而調用未定義的行為。
要解決這個問題,您需要初始化指針,例如在構造函數中:
HeapNode_Min(char d, unsigned f) : d(d),f(f),l(nullptr),r(nullptr) { }
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.