我有以下代码。应该计算给定文件中给定字母的重复次数。但是,当我尝试运行此命令时,我的Vector下标超出了范围。其他有相同错误的人正在尝试访问它的未定义部分,但是我认为这似乎不是问题。

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;
}

最佳答案


(1)创建一个空 vector 。

for(2)循环内部,您尝试使用空 vector 中的索引i访问项目,因此很显然您的索引超出范围。

您首先必须在 vector 中填充一些数据,然后才能访问此数据。

如果要向 vector 添加新项目,则可以使用vector::push_back(这可能是(2)的意思)。

关于c++ - vector 下标超出范围-结构 vector ,我们在Stack Overflow上找到一个类似的问题:https://stackoverflow.com/questions/40659340/

10-11 15:16
查看更多