我正在尝试从文件中读取频率以创建霍夫曼树。我能够做到这一点,但有一个问题。问题在于我使用两个for() loops i and j
并且在该地方重复字母表的地方显示“0”。我的意思是假设字母是"aababccc"
输出是这样的:
a=3,a=0,b=2,a=0,b=0,c=3,c=0,c=0
但我希望输出如下:
a=3, b=2,c=3
我的意思是我必须从我已经完成的内存分配中删除这些零(我将它们存储在sym []和freq []中)。请帮助我这样做(任何语言c或c ++)
int flag[256];
int j = 0;
char sym[256];
int freq[256];
for (i = 0; i < count; i++)
flag[i] = {0};
int fcount1 = 0;
sym[i] = data[i].symbol;
freq[i] = fcount1;
fcount1 = 0;
}
}
给出的输入频率为: abaabbcacaeeded ,存储在 data [index] .symbol 中 与之对应的输出是:
一切都正确,除了这些“0”。请帮我删除这些“0”。
答案 0 :(得分:0)
在j
循环之前,添加一个条件:
if (flag[i] == 0)
此外,使用vectors和push_back动态构建storesym
和storefreq
数组
int flag[256];//this flag is to know if the alphabet is already counted or not.If counted that i set it to "1" other wise it is "0".Please see below in my code
int j = 0,i;
std::vector<char> storesym;
std::vector<int> storefreq;
for (i = 0; i < count; i++)
flag[i] = {0};
int fcount1 = 0;
for (i = 0; i < count; i++)
{
if (flag[i] == 0)
{
for (j = i; j < count; j++)
{
if (data[i].symbol == data[j].symbol && flag[j] == 0)
{
fcount1++;
flag[j] = 1;//**I am setting flag to 1 those alphabets to 1 so that they will not be counted again on next iteration**
}
}
storesym.push_back( data[i].symbol );
storefreq.push_back( fcount1 );
}
fcount1 = 0;
}
cout << endl;
for (i = 0; i < storesym.size(); i++)
{
cout << "storesym[i] :" << storesym[i] << endl;//it stores the symbol.
cout << "storefreq[i] :" << storefreq[i] << endl;//it stores the frequency.
}
答案 1 :(得分:0)
检查它是否为0,如果是'0'则不存储