Reputation: 53
When I try to run my code, it compiles fine, but during runtime it gives an out of range vector error. Can anyone help me out?
I have written my code in Xcode:
#include <cmath>
#include <cstdio>
#include <vector>
#include <iostream>
#include <algorithm>
using namespace std;
int main() {
int numOfRows = 0;
cout << "Enter number of rows: ";
cin >> numOfRows;
vector<vector<int>> vec;
int sizeOfAnotherArray = 0;
int value = 0;
for (int i = 0; i < numOfRows; i++) {
cout << "Enter size of another array: ";
cin >> sizeOfAnotherArray;
vec.resize(numOfRows,vector<int>(sizeOfAnotherArray));
for (int j = 0; j < sizeOfAnotherArray; j++) {
cout << "Store Value: ";
cin >> value;
vec.at(i).at(j) = value;
}
}
for (int i = 0; i < numOfRows; i++) {
for (int j = 0; j < sizeOfAnotherArray; j++) {
cout << vec.at(i).at(j) << " ";
}
cout << "\n";
}
return 0;
}
Upvotes: 0
Views: 547
Reputation: 87959
The odd thing about your code is that you enter sizeOfAnotherArray
multiple times and therefore resize your whole array multiple times. But note that you only change the number of rows. Each row you add will have the latest size but earlier rows will keep the size they originally had.
This means that if one of the later values for sizeOfAnotherArray
is larger than one of the earlier values then you are going to get an out of range error, because the earlier row will still have the smaller size.
I'm guessing that the code you meant to write is this. It creates a ragged array, which is an array where the number of columns varies depending on which row you are on.
cout << "Enter number of rows: ";
cin >> numOfRows;
vector<vector<int>> vec(numRows); // create array with N rows
for (int i = 0; i < numOfRows; i++) {
cout << "Enter size of another array: ";
cin >> sizeOfAnotherArray;
vec.at(i).resize(sizeOfAnotherArray); // resize this row only
for (int j = 0; j < sizeOfAnotherArray; j++) {
...
}
for (int i = 0; i < vec.size(); i++) {
for (int j = 0; j < vec.at(i).size(); j++) { // loop on the size of this row
cout << vec.at(i).at(j) << " ";
}
cout << "\n";
}
Upvotes: 3