简体   繁体   中英

Vector subscript out of range error, C++

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

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.

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.

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 range error.

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

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.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM