返回信息流这段哈夫曼树的编码在读码和判断频率那一段出了很大问题但不知道怎么改,求助大佬
#include<iostream>
#include<fstream>
#include<string>
using namespace std;
const int MAX_N=100;
const int INF=65535;
class HNode
{
public:
char data;
double weight;
int parent;
int lchild;
int rchild;
};
class HuffCode
{
public:
string code;
char huffinfo;
};
class HuffMan
{
public:
HuffMan(){}
~HuffMan(){}
void CreateForest(string filename)
{
int i = 0;
string str;
double fdata;
ifstream readfile;
readfile.open(filename);
getline(readfile, str);
for (i=0;i<(int)str.length();i++)
{
ht[i].data = str[i];
}
snum = (int)str.length();//被编码数据数量
//读取被编码数据出现频率
i=0;
while (!readfile.eof())
{
if ((readfile >> fdata).good())
{
ht[i].weight = fdata;//读数据频率
i++;
for(int j=0;j<(int)str.length();j++)
{
if(ht[i].data==ht[j].data)
{
ht[i].weight=ht[i].weight+ht[j].weight;
ht[j].data=' ';
}
}
}
}
readfile.close();
}
void CreateHuffManTree()
{
//左右孩子
int lnode, rnode;
//最小的两个频率值
double min1, min2;
//初始化为-1
for (int i = 0; i < snum; i++)
{
ht[i].parent = ht[i].lchild = ht[i].rchild = -1;
}//end for -> init result
for (int j = snum; j < 2 * snum - 1; j++)
{
//每次调用初始化
min1 = min2 = INF;
lnode = rnode = -1;
//遍历寻找最小的两个频率值min1和min2
for (int k = 0; k < j; k++)
{
//逐一排查不存在双亲节点
if (ht[k].parent == -1)
{
if (ht[k].weight < min1)//小于最小
{
min2 = min1;//最小赋值给次小
rnode = lnode;//同理下标
min1 = ht[k].weight;//新的最小频率值
lnode = k;//其下标
}
//不小于最小,小于次小
else if (ht[k].weight < min2)
{
min2 = ht[k].weight;
rnode = k;
}
}
}
ht[j].weight = ht[lnode].weight + ht[rnode].weight;//双亲结点权重
ht[j].lchild = lnode;//双亲节点左孩子
ht[j].rchild = rnode;
ht[lnode].parent = j;//原最小频率值所在节点的双亲节点赋值为当前节点j
ht[rnode].parent = j;
ht[j].parent = -1;//双亲节点参与比较,赋值为-1
}
}
bool CreateHuffCode()
{
int f, c;
HuffCode hc;
for (int i = 0; i < snum; i++)//作为hcode下标
{
hc.huffinfo = snum;//从非叶子节点开始
c = i;//下标->左节点
f = ht[i].parent;
while (f != -1)//未到根节点
{
if (ht[f].lchild == c)//找到左节点
{
hc.code.assign("0" + hc.code);//左边较小赋值为0
}
else
{
hc.code.assign("1" + hc.code);//右边赋值为1
}
c = f;//替换为上一层节点
f = ht[f].parent;//上一层的双亲节点
}
hc.huffinfo++;
hcode[i] = hc;//赋值当前编码
hc.code.clear();//清空code内容,进行下一次访问
}//end for
return true;
}
void display()
{
for (int i = 0; i < snum; i++)
{
cout << ht[i].data << ":";//被编码数据
cout << hcode[i].code << endl;//编码
}//end for
cout<<"总文本:";
for (int i = 0; i < snum; i++)
cout<<hcode[i].code;
}
private:
HNode ht[MAX_N];//哈夫曼树
HuffCode hcode[MAX_N];//编码
int snum;//总结点数
};
int main()
{
HuffMan huff;
fstream outfile("data1.txt",ios::out);
outfile<<"Happiness is";
outfile.close();
huff.CreateForest("data1.txt");
huff.CreateHuffManTree();
if (huff.CreateHuffCode())
{
cout << "编码成功" << endl;
}
huff.display();
return 0;
}
这是一条镜像帖。来源:北邮人论坛 / cpp / #95389同步于 2017/5/28
该镜像源已超过 30 天没有更新,可能在源站已被删除。
CPP机器人发帖
关于哈夫曼树的一点小问题
formation
2017/5/28镜像同步2 回复
订阅后,新回复会通过你的通知中心匿名送达。