向量超出范围 - C ++

时间:2013-10-18 04:48:43

标签: c++ vector outofrangeexception

我正在开展一个项目,要求我用c ++制作一个Hangman游戏。我大部分时间都在工作,但是每次用户输入猜测后我都会打印出正确猜出的部分内容。我已经创建了一个代表一个刽子手游戏的类,在这个类中是确定猜测做什么的方法。如果在字典中随机选择的单词中的任何位置发现猜测,我将该char保存到名为currentWord的向量中的相同位置。 currentWord在构造函数中被初始化为包含随机选择的单词长度的“_”(这样它与单词的大小相同,我可以在用户输入猜测时更新它)。例如,如果单词是“半殖民主义”,并且用户的第一个猜测是“i”,我想用字母“i”替换currentWord向量中的“_”。

string tempWord = word;
    for (int i = 0; i < tempWord.size(); i++) {


        u_long location = tempWord.find(guess);
        currentWord->at(location) = tempWord[location];
        tempWord[location] = '_';
    }

我试图将成员变量“word”存储在名为tempWord的临时变量中。然后我从0迭代到tempword的长度。我使用tempWord.find(guess)来查找tempWord中与guess匹配的位置,将其存储到名为location的变量中,然后将该位置的currentWord向量更新为等于该位置的tempWord。由于这只会在第一次找到匹配的char时才会起作用,然后我将tempWord [location]更改为'_',这样下一次通过时,位置会有所不同。但通过这样做,我有时会超出范围错误。如果我发表评论

tempWord[location] = '_';

然后我没有看到这个错误,但只替换了第一次出现。即使我得到这个超出界限的错误,我可以在调试器中看到每个出现都在currentWord向量中被正确替换。这让我很困惑,所以任何帮助将不胜感激!感谢

修改

感谢rapptz建议检查位置是否等于std :: string :: npos,我终于让它工作了。以下是使用该检查的更新代码段:

string tempWord = word;
    for (int i = 0; i < tempWord.size(); i++) {


        u_long location = tempWord.find(guess);
        if (location != std::string::npos) {
            currentWord->at(location) = tempWord[location];
            tempWord[location] = '_';
        }

    }

我也非常喜欢特里斯坦的建议,而且明天最有可能这样做。一旦我这样做,我将发布更新的代码,以防其他人发现它有用。再次感谢!

2 个答案:

答案 0 :(得分:0)

我的猜测是tempword.find(guess)从1开始到单词的长度,而不是0.请分享该函数。

答案 1 :(得分:0)

将此作为评论发布,但在更大的文本框中更容易!您可以像这样避免tempWord副本和for循环:

std::string::size_type location = 0, start_pos = 0; // int would be fine, tbh

while ( (location = word.find(guess, start_pos)) != std::string::npos) {
    currentWord.at(location) = word[location];
    start_pos = location;
}
相关问题