我有以下代码。它应该计算给定文件中给定字母的重复次数。然而,当我尝试运行这个我得到的向量下标超出范围。其他人有相同的错误试图访问它的未定义的部分,但这似乎并不是我认为的问题。向量下标超出范围 - 结构向量
struct letters
{
char letter;
int repetitions=0;
};
void howManyTimes(const string &output)
{
ifstream file(output);
vector <letters> alphabet;
for (int i = 0; i < 'z' - 'a' + 1; i++)
{
alphabet[i].letter = 'a' + i;
}
string line;
while (file.eof() == 0)
{
getline(file, line);
for (char c : line)
{
if(c >= 'a' && c <= 'z')
alphabet[c - 'a'].repetitions++;
else if (c >= 'A' && c >= 'Z')
alphabet[c - 'A'].repetitions++;
}
}
cout << alphabet[10].repetitions;
}
你在哪里填充元素的向量? – UnholySheep
为了使用它,需要初始化矢量。否则,使用push_back('a'+ i)'而不是'operator []'来分配值。 –
如果您想查找唯一项目的出现次数,您应该使用'std :: map'。 – NathanOliver