繁体   English   中英

尝试使用霍夫曼字符串代码更新数组

[英]Trying to update an array with huffman string code

我当前的程序创建了一个霍夫曼树,其中填充了从文本文件中读取的 ascii 字符节点以及它们在文本文件中出现的时间(频率)。 此外,它根据频率为读取的每个字符输出唯一代码,这是使用我的遍历功能完成的。

我的问题:我有这个字符串数组,它可以在我的 huffman 函数中保存所有 256 个 ascii 值的代码,默认情况下,每个元素都设置为一个空字符串。 我一直试图通过将参数传递给我的遍历函数来更新我的数组,但它给了我一个错误。

代码 E0413 - “不存在从 std::string 到 char 的合适转换”

下面是我的部分代码以及对遍历函数中的变量的一些解释:

'character' 是在文本文件中找到的字符

'frequency' 给出一个字符在文本文件中被读取的次数

'traversecode' 是由 traverse 函数生成的霍夫曼代码

我还注释掉了我的 traverse 函数中出现错误的行。

struct node {
    int frequency;
    char character;
    const node *child0;
    const node *child1;

    node(unsigned char c = 0, int i = -1) {
        character = c;
        frequency = i;
        child0 = 0;
        child1 = 0;
    }

    node(const node* c0, const node *c1) {
        character = 0;
        frequency = c0->frequency + c1->frequency;
        child0 = c0;
        child1 = c1;
    }

    bool operator<(const node &a) const {
        return frequency > a.frequency;
    }



    void traverse(string codearray[256], string traversecode = "") const {
        if (child0) {
            child0->traverse(traversecode + '0'); // one line throwing the error
            child1->traverse(traversecode + '1'); // second line that throws me the error
        }
        else {
            codearray[int(character)] = traversecode;
            cout << " " << character << "     ";
            cout << frequency;
            cout << "    " << traversecode << endl;
        }
    }

};

huffman 函数(包含我想要更新的数组的函数)

void huffman(string code[256], const unsigned long long frequency[256]) {
    priority_queue < node > q;
    for (unsigned i = 0; i < 256; i++) {
        if (frequency[i] == 0) {
            code[i] = "";
        }
    }

    for (int i = 0; i < 256; i++)
        if (frequency[i])
            q.push(node(i, frequency[i]));

    while (q.size() > 1) {
        node *child0 = new node(q.top());
        q.pop();
        node *child1 = new node(q.top());
        q.pop();
        q.push(node(child0, child1));
    }

    cout << "CHAR  FREQUENCY  HUFFMAN CODE" << endl;
    q.top().traverse(code);
}

当您对traverse进行递归调用时,您需要提供这两个参数。

child0->traverse(codearray, traversecode + '0');

您目前正在尝试将第二个参数作为第一个参数传递。

另一个可能的问题是您的代码假定char是无符号的。 如果char是有符号的,则对codearray[int(character)]访问将在codearray的边界之外访问,如果字符为“负”(或在使用无符号字符时在 ASCII 表的上半部分)。

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM