0001 struct visit { virtual void operator()( HuffChar & e ) { printf( "%8d", e.weight ); } }; 0002 0003 /****************************************************************************************** 0004 * 无论编码森林由列表、完全堆还是左式堆实现,本测试过程都可适用 0005 * 编码森林的实现方式采用优先级队列时,编译前对应的工程只需设置相应标志: 0006 * DSA_PQ_List、DSA_PQ_ComplHeap或DSA_PQ_LeftHeap 0007 ******************************************************************************************/ 0008 int main ( int argc, char* argv[] ) { //Huffman编码算法统一测试 0009 unsigned int * freq = stat ( argv[1] ); //根据样本文件,统计各字符的出现频率 0010 HuffForest* forest = initForest ( freq ); delete freq; //创建Huffman森林 0011 HuffTree tree = generateTree( forest ); delete forest; print( tree ); //构造Huffman编码树 0012 tree.travLevel( visit() ); printf("\n\n"); //验证:层次遍历序列中,各节点的权重单调非增 0013 HuffTable* table = generateTable ( tree ); //将Huffman编码树转换为编码表 0014 for ( int i = 0; i < N_CHAR; i++ ) //输出编码表 0015 printf ( " %c: %s\n", i + 0x20, * ( table->get ( i + 0x20 ) ) ); 0016 for ( int i = 2; i < argc; i++ ) { //对于命令行传入的每一明文串 0017 Bitmap codeString; //二进制编码串 0018 int n = encode ( table, &codeString, argv[i] ); //将根据编码表生成(长度为n) 0019 decode( tree, &codeString, n ); //利用Huffman编码树,对长度为n的二进制编码串解码 0020 } 0021 delete table; return 0; //释放编码表、编码树 0022 }