作者:jostree 转载请注明出处 http://www.cnblogs.com/jostree/p/4096079.html
使用优先队列实现,需要注意以下几点:
1.在使用priority_queue时,内部需要存储哈夫曼树节点的指针,而不能是节点。因为构建哈夫曼树时,需要把其左右指针指向孩子,而如果储存的是节点,那么孩子的地址是会改变的。同理节点应当使用new在内存中开辟,而不能使用vector,原因是vector在数组大小为2整数次幂时,大小会倍增,开辟新数组并把老数组的数字copy过去,从而也会导致地址变化。
2.优先队列对指针的排列,需要额外写一个比较函数来比较指针指向的节点的大小。bool operator () (wcnode * node1, wcnode * node2) return node1->lessthan(node2);并在定义优先队列时使用这种方法: priority_queue <wcnode*, vector<wcnode*>, compare> 第一个参数是节点类型,第二个参数是优先队列的储存结构,第三个参数是比较函数。
3.C++在写入文件时,由于只能按字节写入,因此需要把8个bit位转化为一个字节,最后不足8位用0补齐,并记录文件总bit数,便于解码。然后写入文件。另写入二进制文件可以使用ofstream out("output.txt",std::ofstream::binary);
4.哈夫曼编码信息包括每种字符的映射,和该文件的总bit数。
其代码如下:
![](https://images.cnblogs.com/OutliningIndicators/ContractedBlock.gif)
1 #include <cstdio> 2 #include <cstdlib> 3 #include <iostream> 4 #include <cstring> 5 #include <fstream> 6 #include <queue> 7 #include <map> 8 #include <vector> 9 using namespace std; 10 class compare; 11 12 class wcnode 13 { 14 public: 15 friend class compare; 16 char word; 17 int count; 18 wcnode* left; 19 wcnode* right; 20 bool lessthan (const wcnode *w)const 21 { 22 return count > w->count; 23 } 24 wcnode(char w='