我的代码计算文件中字母的频率。我的代码:
void incCount (int i, vector<CCount> &chars)
{
int n;
n = chars[i].i;
n++;
chars[i].i = n;
}
void procWord(string word, vector<CCount> &chars)
{
for (int i=0; i<word.length(); i++)
{
bool found = false;
char a = word[i];
for (int j=0; j<chars.size(); j++)
{
if (a == chars[j].c)
{
bool found = true;
incCount(j, chars);
}
}
if (found == false)
{
CCount c; //CCount is a class with a char and int data type.
c.c = a;
c.i = 1;
chars.push_back(c);
}
}
}
int main ()
{
vector<CCount> chars;
string word;
//opening file code here
while (fin >> word) {
procWord(word, chars);
}
return 0;
}
class CCount
{
public:
char c;
int i;
};
代码确实累积了字母数,但是当我打印矢量元素时,我得到this。我使用&#34;这是一个测试数据&#34;作为文件中的测试输入
答案 0 :(得分:4)
您再次定义found
。请参阅注释行。
您正在定义具有相同名称的变量,并且首选大多数局部变量。
bool found = false;
char a = word[i];
for (int j=0; j<chars.size(); j++)
{
if (a == chars[j].c)
{
bool found = true; //this is wrong, just make it found = true;
incCount(j, chars);
}
}