哈夫曼编码和译码c++
时间: 2023-10-14 21:05:56 浏览: 110
项目4_哈夫曼树_C++_最优01编码_
哈夫曼编码是一种可变长度编码,用于将字符转换为二进制码。它的主要思想是将出现频率较高的字符用较短的编码表示,出现频率较低的字符用较长的编码表示,以此来减少编码后的总长度。哈夫曼编码的实现需要构建哈夫曼树,然后根据哈夫曼树生成每个字符的编码。
以下是哈夫曼编码和译码的C++代码示例:
```c++
#include <iostream>
#include <queue>
#include <unordered_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;
}
};
// 构建哈夫曼树
Node* buildHuffmanTree(string s) {
// 统计每个字符出现的频率
unordered_map<char, int> freqMap;
for (char c : s) {
freqMap[c]++;
}
// 将每个字符及其频率存入优先队列中
priority_queue<Node*, vector<Node*>, cmp> pq;
for (auto& p : freqMap) {
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);
}
return pq.top();
}
// 生成哈夫曼编码
void generateHuffmanCode(Node* root, string code, unordered_map<char, string>& codeMap) {
if (!root) {
return;
}
if (root->ch != '$') {
codeMap[root->ch] = code;
}
generateHuffmanCode(root->left, code + "0", codeMap);
generateHuffmanCode(root->right, code + "1", codeMap);
}
// 哈夫曼编码
string huffmanEncode(string s) {
Node* root = buildHuffmanTree(s);
unordered_map<char, string> codeMap;
generateHuffmanCode(root, "", codeMap);
string encodedStr = "";
for (char c : s) {
encodedStr += codeMap[c];
}
return encodedStr;
}
// 哈夫曼译码
string huffmanDecode(string s, Node* root) {
string decodedStr = "";
Node* cur = root;
for (char c : s) {
if (c == '0') {
cur = cur->left;
} else {
cur = cur->right;
}
if (cur->ch != '$') {
decodedStr += cur->ch;
cur = root;
}
}
return decodedStr;
}
int main() {
string s = "hello world";
string encodedStr = huffmanEncode(s);
cout << "Encoded string: " << encodedStr << endl;
Node* root = buildHuffmanTree(s);
string decodedStr = huffmanDecode(encodedStr, root);
cout << "Decoded string: " << decodedStr << endl;
return 0;
}
```
阅读全文