哈夫曼编码C++实现

哈夫曼编码、译码算法的c++实现,将功能模块封装成类Huffman

 

下载地址:http://download.csdn.net/source/1409937

 

文件main.cpp

 

 


 

文件Huffman.h

 

 

 


 

文件Huffman.cpp

  • 3
    点赞
  • 8
    收藏
    觉得还不错? 一键收藏
  • 8
    评论
哈夫曼编码是一种可变字长编码方式,它可以将不同长度的字符编码为等长的二进制码,从而实现数据的压缩。下面是C++实现哈夫曼编码的代码: #include <iostream> #include <queue> #include <vector> #include <string> #include <map> using namespace std; struct Node { char ch; int freq; Node* left; Node* right; Node(char c, int f) : ch(c), freq(f), left(nullptr), right(nullptr) {} }; struct cmp { bool operator()(Node* a, Node* b) { return a->freq > b->freq; } }; void encode(Node* root, string str, map<char, string>& huffmanCode) { if (!root) { return; } if (!root->left && !root->right) { huffmanCode[root->ch] = str; } encode(root->left, str + "0", huffmanCode); encode(root->right, str + "1", huffmanCode); } void decode(Node* root, int& index, string str) { if (!root) { return; } if (!root->left && !root->right) { cout << root->ch; return; } index++; if (str[index] == '0') { decode(root->left, index, str); } else { decode(root->right, index, str); } } void buildHuffmanTree(string text) { map<char, int> freq; for (char c : text) { freq[c]++; } priority_queue<Node*, vector<Node*>, cmp> pq; for (auto p : freq) { pq.push(new Node(p.first, p.second)); } while (pq.size() > 1) { Node* left = pq.top(); pq.pop(); Node* right = pq.top(); pq.pop(); Node* parent = new Node('$', left->freq + right->freq); parent->left = left; parent->right = right; pq.push(parent); } Node* root = pq.top(); map<char, string> huffmanCode; encode(root, "", huffmanCode); cout << "Huffman Codes are:\n" << endl; for (auto p : huffmanCode) { cout << p.first << " : " << p.second << endl; } cout << "\nOriginal string was:\n" << text << endl; string encodedString = ""; for (char c : text) { encodedString += huffmanCode[c]; } cout << "\nEncoded string is:\n" << encodedString << endl; int index = -1; cout << "\nDecoded string is:\n"; while (index < (int)encodedString.size() - 2) { decode(root, index, encodedString); } }
评论 8
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值