C++ 为什么指标有时有效,有时无效?写下哈夫曼密码
我遇到了一个问题,因为我正在编写一个简化版的哈夫曼编码,而我在创建代码时遇到了一个问题,也就是说,当程序每秒都不工作时,我不知道是什么原因,我收到了一条消息“thread1:EXC_BAD_ACCESS(code=1,address=0x0)”,我没有包括整个代码,因为我想这是不必要的C++ 为什么指标有时有效,有时无效?写下哈夫曼密码,c++,C++,我遇到了一个问题,因为我正在编写一个简化版的哈夫曼编码,而我在创建代码时遇到了一个问题,也就是说,当程序每秒都不工作时,我不知道是什么原因,我收到了一条消息“thread1:EXC_BAD_ACCESS(code=1,address=0x0)”,我没有包括整个代码,因为我想这是不必要的 #包括 #包括 #包括 #包括 #包括 #包括 使用名称空间std; int计数器=0; 结构字符 { 字符a; 字符串代码; 未署名的长相; 字符*左,*右; }; 结构huffman_代码 { 字符a;
#包括
#包括
#包括
#包括
#包括
#包括
使用名称空间std;
int计数器=0;
结构字符
{
字符a;
字符串代码;
未署名的长相;
字符*左,*右;
};
结构huffman_代码
{
字符a;
字符串代码;
};
创建代码的函数,下面是图片附带的问题
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);
}
}
void编码(字符*根、字符串str、向量和huffmanCode)
{
if(root==nullptr)
返回;
//找到一个叶节点
如果(!root->left&!root->right){
huffmanCode[counter]。code=str;**问题已解决**
huffmanCode[计数器].a=根->a;
计数器++;
}
编码(根->左,str+“0”,huffmanCode);
编码(根->右,str+“1”,huffmanCode);
}
}
intmain()
{
向量多少次;
多少次。保留(26);
字符串C=“abcdefghijklmnoprqestuvxyz”,rows=“abbceeddff”;
优先级队列Q;
字符*w;
无符号长多少;
对于(int i=0;i您从未向添加元素多少次
或huffmanCode
;您只为它们保留了空间
对那些不存在的元素(特别是赋值)的每次访问都有未定义的行为
你需要重读你书中关于使用向量的章节
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;
}