哈夫曼编码c++用类实现
时间: 2023-11-16 22:56:39 浏览: 101
下面是一个用C++类实现哈夫曼编码的例子,代码如下:
```
#include <iostream>
#include <queue>
#include <vector>
#include <string>
#include <map>
using namespace std;
class HuffmanNode {
public:
char data;
int freq;
HuffmanNode* left;
HuffmanNode* right;
HuffmanNode(char data, int freq) {
this->data = data;
this->freq = freq;
left = right = NULL;
}
};
class Compare {
public:
bool operator()(HuffmanNode* a, HuffmanNode* b) {
return a->freq > b->freq;
}
};
class Huffman {
public:
Huffman(string text) {
for (int i = 0; i < text.length(); i++) {
freq[text[i]]++;
}
priority_queue<HuffmanNode*, vector<HuffmanNode*>, Compare> pq;
for (auto i : freq) {
pq.push(new HuffmanNode(i.first, i.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);
}
root = pq.top();
encode(root, "");
}
void encode(HuffmanNode* root, string str) {
if (!root) {
return;
}
if (root->data != '$') {
codes[root->data] = str;
}
encode(root->left, str + "0");
encode(root->right, str + "1");
}
string getEncodedText(string text) {
string encodedText = "";
for (int i = 0; i < text.length(); i++) {
encodedText += codes[text[i]];
}
return encodedText;
}
string getDecodedText(string encodedText) {
string decodedText = "";
HuffmanNode* curr = root;
for (int i = 0; i < encodedText.length(); i++) {
if (encodedText[i] == '0') {
curr = curr->left;
}
else {
curr = curr->right;
}
if (curr->data != '$') {
decodedText += curr->data;
curr = root;
}
}
return decodedText;
}
private:
map<char, int> freq;
map<char, string> codes;
HuffmanNode* root;
};
int main() {
string text = "hello world";
Huffman h(text);
string encodedText = h.getEncodedText(text);
string decodedText = h.getDecodedText(encodedText);
cout << "Original text: " << text << endl;
cout << "Encoded text: " << encodedText << endl;
cout << "Decoded text: " << decodedText << endl;
return 0;
}
```
这个例子中,我们定义了一个`HuffmanNode`类来表示哈夫曼树的节点,其中包含了字符数据、出现频率、左右子节点等信息。我们还定义了一个`Huffman`类来实现哈夫曼编码的功能,其中包含了计算字符频率、构建哈夫曼树、生成编码、编码文本、解码文本等方法。在构建哈夫曼树时,我们使用了一个优先队列来存储节点,并按照频率从小到大排序。在生成编码时,我们使用了递归的方式遍历哈夫曼树,并记录每个字符的编码。在编码文本时,我们根据字符的编码将其转换为二进制字符串。在解码文本时,我们根据二进制字符串遍历哈夫曼树,直到找到叶子节点,然后将其对应的字符加入到解码文本中。
阅读全文