pat des pat
pat des pat

Reputation: 127

vector subscript out of range during compiling

int i = 0;
int j = 0;

vector<vector<int>> normal;
vector< vector<int> >::iterator row;
vector<int>::iterator col;

for (i = 1; i < 10; i++) {
    for (j = 1; j < 10; j++) {
         normal[i].push_back(j);

    }
}

Can someone explain me what l am doing wrong? during my compiling I got the error "Vector subscript out of range"

Upvotes: 7

Views: 851

Answers (3)

Xian Zhang
Xian Zhang

Reputation: 61

Vector normal is empty. You can initialize vector as follow.

vector<vector<int>> normal(10, vector<int>());

Upvotes: 6

Brandon Dyer
Brandon Dyer

Reputation: 1386

You haven't put anything into normal. It sits as an empty vector until you put something into it.

You can fix this problem by giving it a new value each iteration

for (i = 0; i < 10; i++) {
    normal.push_back(vector<int>());
    for (j = 0; j < 10; j++) {
         normal[i].push_back(j);
    }
}

Also, your i and j were being initialized to 1, but I'm fairly certain you meant 0. I addressed this in my snippet.

Upvotes: 6

Scott Hunter
Scott Hunter

Reputation: 49893

You never add any elements to normal before trying to use normal[i].

Upvotes: 10

Related Questions