哈夫曼编码和译码C++
时间: 2023-12-11 17:33:13 浏览: 109
项目4_哈夫曼树_C++_最优01编码_
以下是C++实现哈夫曼编码和译码的示例代码:
```cpp
#include <iostream>
#include <queue>
#include <vector>
#include <unordered_map>
using namespace std;
// 哈夫曼树节点
struct HuffmanNode {
char ch; // 字符
int freq; // 频率
HuffmanNode* left; // 左子节点
HuffmanNode* right; // 右子节点
HuffmanNode(char c, int f) : ch(c), freq(f), left(nullptr), right(nullptr) {}
};
// 哈夫曼树节点比较器
struct Compare {
bool operator()(HuffmanNode* a, HuffmanNode* b) {
return a->freq > b->freq;
}
};
// 构建哈夫曼树
HuffmanNode* buildHuffmanTree(const string& str) {
// 统计字符频率
unordered_map<char, int> freqMap;
for (char c : str) {
freqMap[c]++;
}
// 构建哈夫曼树
priority_queue<HuffmanNode*, vector<HuffmanNode*>, Compare> pq;
for (auto& p : freqMap) {
pq.push(new HuffmanNode(p.first, p.second));
}
while (pq.size() > 1) {
HuffmanNode* left = pq.top();
pq.pop();
HuffmanNode* right = pq.top();
pq.pop();
HuffmanNode* parent = new HuffmanNode('*', left->freq + right->freq);
parent->left = left;
parent->right = right;
pq.push(parent);
}
return pq.top();
}
// 生成哈夫曼编码
void generateHuffmanCode(HuffmanNode* root, string code, unordered_map<char, string>& codeMap) {
if (!root) {
return;
}
if (!root->left && !root->right) {
codeMap[root->ch] = code;
}
generateHuffmanCode(root->left, code + "0", codeMap);
generateHuffmanCode(root->right, code + "1", codeMap);
}
// 哈夫曼编码
string huffmanEncode(const string& str) {
// 构建哈夫曼树
HuffmanNode* root = buildHuffmanTree(str);
// 生成哈夫曼编码
unordered_map<char, string> codeMap;
generateHuffmanCode(root, "", codeMap);
// 编码
string encodedStr;
for (char c : str) {
encodedStr += codeMap[c];
}
return encodedStr;
}
// 哈夫曼译码
string huffmanDecode(const string& str, HuffmanNode* root) {
string decodedStr;
HuffmanNode* cur = root;
for (char c : str) {
if (c == '0') {
cur = cur->left;
} else {
cur = cur->right;
}
if (!cur->left && !cur->right) {
decodedStr += cur->ch;
cur = root;
}
}
return decodedStr;
}
int main() {
string str = "abaccdaA";
string encodedStr = huffmanEncode(str);
cout << "Encoded string: " << encodedStr << endl;
HuffmanNode* root = buildHuffmanTree(str);
string decodedStr = huffmanDecode(encodedStr, root);
cout << "Decoded string: " << decodedStr << endl;
return 0;
}
```
阅读全文