Reputation: 21
Trying to traverse a 2d vector in order to find index(es) of a certain key value which is the number 1. I looked up what a segmentation fault was and it said that it happens when you try to access too much memory, but I don't get how I'm doing that.
#include<iostream>
#include<algorithm>
#include <vector>
#include <cmath>
using namespace std;
int main(){
vector<vector<int>> matrix;
int n;
int i = 0;
int j = 0;
for (int i =0; i<5; i++){
for (int z = 0; z<5; z++){
cin >> n;
matrix[i][z] = n;
}
}
while (matrix[i][j] != 1 && ((i && j) < matrix.size())){
while (i != 5){
i++;
while (j != 5){
j++;
}
}
}
cout << abs((2-j) + (2-i)) << endl;
}
Upvotes: 0
Views: 76
Reputation: 5080
To fix the segfault, you have to change the declaration of your vector to
vector<vector<int>> matrix(5, vector<int>(5));
Now it has enough capacity to store the elements.
The first parameter is the number of elements that the vector supports initially, which is 5.
The second parameter is the default object the vector will hold when initializes. In this case, for each one of the first five slots of the first dimension, the default object will be a vector of capacity 5.
Upvotes: 1