哈夫曼编译码器c++
时间: 2024-02-09 15:05:21 浏览: 25
以下是一个C++实现的哈夫曼编译码器的示例代码:
```cpp
#include <iostream>
#include <queue>
#include <unordered_map>
using namespace std;
// 哈夫曼树节点
struct Node {
char data;
int freq;
Node* left;
Node* right;
Node(char data, int freq) {
this->data = data;
this->freq = freq;
left = right = nullptr;
}
};
// 用于比较节点频度的函数对象
struct Compare {
bool operator()(Node* left, Node* right) {
return left->freq > right->freq;
}
};
// 构建哈夫曼树
Node* buildHuffmanTree(const unordered_map<char, int>& freqMap) {
priority_queue<Node*, vector<Node*>, Compare> pq;
// 将每个字符的频度作为节点加入优先队列
for (const auto& pair : freqMap) {
pq.push(new Node(pair.first, pair.second));
}
// 从优先队列中取出两个频度最小的节点,合并为一个新节点,直到只剩下一个节点
while (pq.size() > 1) {
Node* left = pq.top();
pq.pop();
Node* right = pq.top();
pq.pop();
Node* newNode = new Node('$', left->freq + right->freq);
newNode->left = left;
newNode->right = right;
pq.push(newNode);
}
return pq.top();
}
// 递归构建哈夫曼编码表
void buildHuffmanCodes(Node* root, string code, unordered_map<char, string>& codes) {
if (root == nullptr) {
return;
}
if (root->data != '$') {
codes[root->data] = code;
}
buildHuffmanCodes(root->left, code + "0", codes);
buildHuffmanCodes(root->right, code + "1", codes);
}
// 哈夫曼编码
string encode(const string& text, const unordered_map<char, string>& codes) {
string encodedText = "";
for (char c : text) {
encodedText += codes.at(c);
}
return encodedText;
}
// 哈夫曼译码
string decode(const string& encodedText, Node* root) {
string decodedText = "";
Node* curr = root;
for (char bit : encodedText) {
if (bit == '0') {
curr = curr->left;
} else {
curr = curr->right;
}
if (curr->left == nullptr && curr->right == nullptr) {
decodedText += curr->data;
curr = root;
}
}
return decodedText;
}
// 打印哈夫曼树
void printHuffmanTree(Node* root) {
if (root == nullptr) {
return;
}
cout << root->data << " - " << root->freq << endl;
printHuffmanTree(root->left);
printHuffmanTree(root->right);
}
int main() {
string text = "hello world";
// 统计字符频度
unordered_map<char, int> freqMap;
for (char c : text) {
freqMap[c]++;
}
// 构建哈夫曼树
Node* root = buildHuffmanTree(freqMap);
// 构建哈夫曼编码表
unordered_map<char, string> codes;
buildHuffmanCodes(root, "", codes);
// 哈夫曼编码
string encodedText = encode(text, codes);
cout << "Encoded text: " << encodedText << endl;
// 哈夫曼译码
string decodedText = decode(encodedText, root);
cout << "Decoded text: " << decodedText << endl;
// 打印哈夫曼树
cout << "Huffman tree:" << endl;
printHuffmanTree(root);
return 0;
}
```