Vector subscript out of range [closed]
I'm getting the vector subscript out of range error. I've had it before, but it prints 'before' but it doesn't print 'after' so I'm confused at to why one of these lines would be causing it.
cout << "before" << endl;
vector<vector<char>> animals;
vector<vector<char>> food;
vector<char> other;
int lastline = 0;
for(int i=1;i<=(c);i++){
cout << "after" << endl;
If c
is the count of elements in any vector, then the mistake is simply that in a vector with N
items the item indexes are 0...[N-1]
and not 1...N
.
Therefore, make this correction:
for(int i=0; i < (c); i++) {
By the way, in C-like languages the archetype of a for
loop that iterates N
times is, not coincidentally:
for(int i = 0; i < N; ++i)
Stick with this unless you have a very very good reason to make an exception, and you get to avoid this type of bug "for free".
精彩评论