使用stl和无节点c ++

时间:2018-12-09 20:12:27

标签: c++ compression huffman-code

该代码必须为字符串中的字符打印霍夫曼代码,但对于某些字符却给出了错误的代码(主要是在结尾处获得代码1的带壳人

#include<iostream>
#include<string>
#include<map>
#include<queue>

using namespace std;

struct compare {
    bool operator()(pair<char, int> l, pair<char, int> r) {
        return r.second > l.second;
    }

};

map<char, int> frequencies(string str) {
    map<char, int> result;
    for (int i = 0; i < str.length(); i++) {
        if (result.find(str[i]) != result.end())
            result[str[i]]++;
        else
            result[str[i]] = 1;
    }
    return result;
}

void print(const map<char, int> a) {
    for (map<char, int>::const_iterator it = a.begin(); it != a.end(); it++) {
        cout << (it->first) << " " << (it->second) << endl;
    }

}

void prints(const map<char, string> a) {
    for (map<char, string>::const_iterator it = a.begin(); it != a.end(); it++) {
        cout << (it->first) << " " << (it->second) << endl;
    }

}

map<char, string> huffman(map<char, int> a) {
    priority_queue < pair < char, int >, vector < pair < char, int > >, compare > mappednodes;
    pair<char, int> root;
    pair<char, int> left, right;
    string s = "";
    map<char, string> result;

    for (map<char, int>::iterator itr = a.begin(); itr != a.end(); itr++) {
        mappednodes.push(pair<char, int>(itr->first, itr->second));
    }
    while (mappednodes.size() != 1) {
        left = mappednodes.top();
        mappednodes.pop();
        right = mappednodes.top();
        mappednodes.pop();
        root = make_pair('#', left.second + right.second);
        mappednodes.push(root);
        if (left.first != '#') {
            s = "0" + s;
            result[left.first] = s;
        }

        if (right.first != '#') {
            s = "1" + s;
            result[right.first] = s;
        }
    }
    return result;
}

int main() {
    string str;
    cout << "enter the string ";
    getline(cin, str);
    cout << endl;
    map<char, int> freq = frequencies(str);
    print(freq);
    cout << endl;
    map<char, string> codes = huffman(freq);
    prints(codes);


}

例如字符串sasi 它必须给出

  • s 0
  • i 10
  • 一个11

但它给予了

  • s 0
  • i 10
  • 一个110

https://www.geeksforgeeks.org/huffman-coding-greedy-algo-3/

以此为基础,但一无所获

1 个答案:

答案 0 :(得分:0)

问题是您只需要在循环中向s添加字符(“位”)即可。