我有一个问题,因为我正在编写霍夫曼编码的简化版本,并且在创建代码时遇到问题,即第二次该程序不起作用并且我不知道是什么原因,我得到了此消息“线程1:EXC_BAD_ACCESS(代码= 1,地址= 0x0)”我没有包括整个代码,因为我认为这是不必要的。
#include<iostream>
#include<cstdlib>
#include<vector>
#include<string.h>
#include<queue>
#include<cstddef>
using namespace std;
int counter = 0;
struct characters
{
char a;
string code;
unsigned long likehood;
characters *left, *right;
};
struct huffman_code
{
char a;
string code;
};
创建代码的函数,这是图片附带的问题。
void encode(characters* root, string str, vector<huffman_code> &huffmanCode)
{
if (root == nullptr)
return;
// found a leaf node
if (!root->left && !root->right) {
huffmanCode[counter].code = str; **PROBLEM IS HEAR**
huffmanCode[counter].a = root->a;
counter++;
}
encode(root->left, str + "0", huffmanCode);
encode(root->right, str + "1", huffmanCode);
}
}
int main()
{
vector<characters> how_many_times;
how_many_times.reserve(26);
string C="abcdefghijklmnoprqestuvwxyz", rows="abbceeeddfff";
priority_queue<characters*, vector<characters*>, characters_comparsion> Q;
characters *w;
unsigned long how_many;
for(int i=0; i<26; i++)
{
how_many_times[i].a = C[i];
how_many_times[i].likehood=0;
how_many_times[i].left = NULL;
how_many_times[i].right = NULL;
}
unsigned long length = rows.length();
for(unsigned long i=0; i<length; i++)
{
for(int j=0; j<26; j++)
{
if(how_many_times[j].a==rows[i])
{
how_many_times[j].likehood++;
break;
}
}
}
for(unsigned long i=0; i<26; i++)
{
if(how_many_times[i].likehood!=0)
{
Q.push(&how_many_times[i]);
}
}
how_many = Q.size();
vector<huffman_code> huffmanCode;
huffmanCode.reserve(how_many);
w = Huffman(Q);
encode(w, "", huffmanCode);
cout<<"Cody Huffmana: "<<endl;
for(int i=0; i<how_many; i++)
{
cout<<huffmanCode[i].a<<" "<<huffmanCode[i].code<<endl;
}
return 0;
}
您从未在how_many_times
或huffmanCode
中添加元素;您只为他们保留了空间。