向量下标超出范围错误,C++

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/5161554/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me): StackOverFlow

提示:将鼠标放在中文语句上可以显示对应的英文。显示中英文
时间:2020-08-28 17:33:31  来源:igfitidea点击:

Vector subscript out of range error, C++

c++filevector

提问by charli

When I try to run this program I get an error that halts the program and says, "Vector subscript out of range"

当我尝试运行这个程序时,我收到一个错误,该错误会停止程序并显示“向量下标超出范围”

Any idea what I'm doing wrong?

知道我做错了什么吗?

#include <vector>
#include <string>
#include <iostream>
#include <iomanip>
#include <fstream>
#include <sstream>
using namespace std;

//(int argc, char* argv[]
int main()
{
    fstream bookread("test.txt");
    vector<string> words;

    bookread.open("test.txt");
    if(bookread.is_open()){
        cout << "opening textfile";
        while(bookread.good()){
            string input;
            //getline(bookread, input);
            bookread>>input;
            //string cleanedWord=preprocess(input);         
            //char first=cleanedWord[0];
            //if(first<=*/
            //cout << "getting words";
            //getWords(words, input);
        }
    }
    cout << "all done";

    words[0];

getchar();
}

回答by Axel Gneiting

You never insert anything into the words vector, so the line words[0];is illegal, because it accesses the first element of it, which does not exist.

你永远不会在 words 中插入任何东西vector,所以该行words[0];是非法的,因为它访问了它的第一个元素,它不存在。

回答by dma

I don't see where you're pushing anything on to the vector. If the vector is empty, subscript 0 would be out of range.

我看不出你在哪里将任何东西推到向量上。如果向量为空,则下标 0 将超出范围。

回答by quamrana

It seems that your program never gets round to adding anything to the vector, usually done with push_back(), so at run-time words[0]produces your subscript out of rangeerror.

似乎您的程序永远不会向向量添加任何内容,通常使用 完成push_back(),因此在运行时words[0]会产生您的subscript out of range错误。

You should check the size of the vector before accessing it.

您应该在访问之前检查向量的大小。

Try this:

尝试这个:

for(vector<string>::const_iterator it=words.begin(), end=words.end(); it!=end; ++it){
  cout << *it << ' ';
}

回答by user640121

Can you please attach the version of the code where you actually push_back strings on the vector. Its not possible to debug the issue unless the code on which reproduce is available for review.

你能附上代码的版本吗,你实际上在向量上推回字符串。除非重现的代码可供,否则无法调试问题。