为什么不分析向量词的最后一个元素以及它如何超出范围?

问题描述 投票:0回答:1

我成功打印了六位、三位和二位的数量,但没有打印出一个,并且在我返回 0 后,程序因超出 words 的范围而出错;

int main()
{
    vector<string> words;
    words.push_back("Six");
    words.push_back("Six");
    words.push_back("Six");
    words.push_back("Six");
    words.push_back("Six");
    words.push_back("Six");
    words.push_back("Three");
    words.push_back("Three");
    words.push_back("Three");
    words.push_back("Two"); 
    words.push_back("Two");
    words.push_back("One");

    vector<int> values; // vector to tracks the # of times a string
                        //appears in the vecotor words

    //create elements in values equal to number of 
    //elements in words
    //note: this creates too many elements
    //I am aware but am a begginner and don't know how
    //to solve this issue
    for (int i = 0; i <= words.size() - 1; i++) 
    {
        values.push_back(0);
    }

    int invariant = 0; // tracks number of times loops
    string current; // used make sure duplicate strings aren't recounted

    while (invariant <= words.size() - 1) 
    {
        //compare each element of words to each other element 
        //one at a time and increment the appropriate
        //element of values if they match
        for (int i = 0; i <= words.size() - 1; i++)
        {
            if (words[invariant] == words[i])
            {
                values[invariant] = values[invariant] + 1;
            }
        }
        //used to check for duplicate strings
        current.clear();
        current = words[invariant];

        if (invariant + 1 > words.size()) //avoids going outside range of words
        {
            return 0; //Errors outside range after this return
        }
        else{
            if (words[invariant+1] == current) // if the next word is the same
            {
                ++invariant;
            }
            else //if the next word is different output the number of times the current word appears
            {
                cout << current << " appears " << values[invariant] << " times.\n";
                ++invariant;
            }
        }
    }
    return 0;
}

我已经在这个代码上工作了几个小时,终于达到了这一点。我自学 C++ 已经一周了。如何检查当前单词是否等于下一个单词而不超出最后的范围。

注意:我通常使用不变式 <= value for loops but without invariant == value - 1 the program would error out for being outside range of words.

程序的目标是输出words中的每个字符串在words中出现了多少次。

c++ vector range
1个回答
0
投票

对于你的第一个问题,你应该这样做:

vector<int> values(words.size());

初始化时。

此代码:

if (invariant + 1 > words.size())

让不变量超越向量的边界。

你应该这样做:

if(invariant == words.size())

© www.soinside.com 2019 - 2024. All rights reserved.