霍夫曼树中的换行符

时间:2019-05-26 01:54:49

标签: c++ class huffman-code

我的霍夫曼树应该打印

CR,用于显示字符“ \ n” LF,用于显示字符“ \ r”

但是它只打印一个空格。

到目前为止,这是我的代码:

#include <cmath>
#include <fstream>
#include <iostream>
#include <map>
#include <vector>
#include <queue>

#define MAX_TREE_HT 2048

using namespace std;

// map characters to value
map<char, string> codes;

// store frequences
map<char, int> freq;

// Create tree.
struct HuffmanTree {
    char data;                 // One of the input characters
    int freq;                  // Frequency of the character
    HuffmanTree *left, *right; // Left and right child

    HuffmanTree(char data, int freq) {
        left = right = NULL;
        this->data = data;
        this->freq = freq;
    }
};

// Compare Function
struct compare {
    bool operator()(HuffmanTree* l, HuffmanTree* r) { return (l->freq > r->freq); }
};

void printCodes(struct HuffmanTree* root, string str) {
    if(!root) return;
    if(root->data != '$') cout << root->data << ": " << str << "\n";
    printCodes(root->left, str + "0");
    printCodes(root->right, str + "1");
}

void storeCodes(struct HuffmanTree* root, string str) {
    if(root == NULL) return;
    if(root->data != '$') codes[root->data] = str;
    storeCodes(root->left, str + "0");
    storeCodes(root->right, str + "1");
}

// Use vector and queue
//
priority_queue<HuffmanTree*, vector<HuffmanTree*>, compare> minHeap;

// build tree and store codes
void HuffmanCodes(int size) {
    struct HuffmanTree *left, *right, *top;
    for(map<char, int>::iterator v = freq.begin(); v != freq.end(); v++)
        minHeap.push(new HuffmanTree(v->first, v->second));
    while(minHeap.size() != 1) {
        left = minHeap.top();
        minHeap.pop();
        right = minHeap.top();
        minHeap.pop();
        top = new HuffmanTree('$', left->freq + right->freq);
        top->left = left;
        top->right = right;
        minHeap.push(top);
    }
    storeCodes(minHeap.top(), "");
}

// map frequencies
void calcFreq(string str, int n) {
    for(int i = 0; i < str.size(); i++) freq[str[i]]++;
}

int main() {
    ifstream t("file.txt");
    string str((std::istreambuf_iterator<char>(t)),
               std::istreambuf_iterator<char>());

    string encodedString;
    calcFreq(str, str.length());
    HuffmanCodes(str.length());
    for(auto v = codes.begin(); v != codes.end(); v++)
        cout << "{key: " << v->first << ' ' << v->second << "}" << endl;

    return 0;
}

这是示例输入文件“ file.txt”:

This is a test line. 
This is a test line. 
This is a test line. 

以下是输出:

{key:
 10100}
{key:   111}
{key: T 10101}
{key: a 01101}
{key: e 001}
{key: f 01100}
{key: h 0100}
{key: i 110}
{key: l 1011}
{key: n 0111}
{key: s 100}
{key: t 000}
{key: w 0101}

这是基本的霍夫曼树,没有任何花哨。我只需要映射换行和回车的频率。我正在Windows 10上运行的Ubuntu中使用g ++编译。

0 个答案:

没有答案