首页 > 解决方案 > 还有其他关于向量的知识吗

问题描述

我最近做了一个简短的程序,关于我在网上学到的关于编程的新课程(我是 C++ 的初学者),每次我学习一个新概念时我都会这样做,以深入了解它的概念和它的用途。(这是我在编程中自学的方式)。我在我的程序中使用了矢量,它解决了我的问题。但是,它创造了一个新的。

(您可能已经看过这段代码)

#include <iostream>
#include <string>
#include <windows.h>
#include <vector>

using namespace std;

int main()
{
    string LetterInput, LetterLoad, input;
    string Words[5] = {"fire","eggs","roll","camera","lotion"};
    vector <string> PossibleAnswers;
    int Number,a = 0;
    int Size,Num;

    cout << "Lets play HANGMAN! " << endl;
    Sleep(500);

    cout << "Think of a word and type in the number" << endl;
    cout << "of letters there are" << endl;
    cin >> Size;

    for (int i = 0; i <= Size; i++){
        LetterLoad += "_";
    }

    Num = sizeof(Words)/sizeof(string);

    for (int i = 0; i <= Num ; i++){
        if ((unsigned)Size == Words[i].size()){
            PossibleAnswers.push_back(Words[i]);
        }
    }


    for (int i = 0;i <= Num;i++){
        cout << PossibleAnswers[i] << endl;
    }

    cout << "Okay lets start" << endl;
    Sleep(750);

    while(a == 0)
   {

    cout << PossibleAnswers[0] << endl;
    cout << PossibleAnswers[1] << endl;

    cout << LetterLoad << endl;

    cout << "Type in the position of the letter you want to guess" << endl;
    cin >> Number;

    cout << "What letter do you want to put?" << endl;
    cin >> LetterInput;

    LetterLoad[Number-1] = LetterInput[0];

   for (size_t i = 0; i <= PossibleAnswers.size(); i++){
    for (int n = 0; n <= Size; n++){
        if (LetterInput[n] == PossibleAnswers[i][n]){
            cout << "Got one" << endl;
        }
    }
   }

   }
    return 0;

}

该程序能够采取正确的措辞。但是,当它即将到达该cout << "Okay lets start" << endl;代码行下方的所有内容时,它就会停止工作。我听说向量需要其他人的“内存分配”。这与程序运行不正常有关吗?我该如何解决?

标签: c++arraysstringvector

解决方案


如果if ((unsigned)Size == Words[i].size()){任何数量的情况都不满足条件,那么您将没有推回足够多的字符串。发生这种情况时,您会在以下for (int i = 0;i <= Num;i++){循环中崩溃,因为您正在尝试访问您拥有的更多元素。我会建议这样做:

for (std::string &s : PossibleAnswers){
    std::cout << s << std::endl;
}

你也可以从0to循环PossibleAnswers.size(),就像你在下面做的那样。

我听说向量需要其他人的“内存分配”。

不,你一定是误会了什么。这只是一个超出范围的错误,我建议通过始终使用基于范围的 for 循环或循环 from 0to 来循环向量来避免这些错误vec.size()


推荐阅读