[英]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.