Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Vector subscript out of range error, C++

Tags:

c++

file

vector

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();
}
like image 383
charli Avatar asked Mar 01 '11 23:03

charli


People also ask

What is a vector subscript?

A vector subscript is an integer array expression of rank one, designating a sequence of subscripts that correspond to the values of the elements of the expression. A vector subscript can be a real array expression of rank one in XL Fortran.

What does vector subscript out of range mean C++?

vector subscript out of range means "you asked for an element from the vector, but the vector is not of that size". e.g. vector<int> vec; vec.push_back(42); vec[1] // oops, 42 is vec[0]

What is the vector in C++?

Vectors in C++ are sequence containers representing arrays that can change their size during runtime. They use contiguous storage locations for their elements just as efficiently as in arrays, which means that their elements can also be accessed using offsets on regular pointers to its elements.


2 Answers

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.

like image 62
Axel Gneiting Avatar answered Sep 28 '22 09:09

Axel Gneiting


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.

like image 23
dma Avatar answered Sep 28 '22 08:09

dma