I am trying to create a 2D array using vector. I have written the following code:
int main() {
vector< vector<int> > v;
int i, j;
for(i=0; i<11; i++)
for(j=0; j<11; j++)
v[i].push_back(j);
for(i=0; i<11; i++) {
for(j=0; j<11; j++)
cout<<v[i][j]<<" ";
cout<<endl;
}
return 0;
}
Now I was expecting it to print the numbers 0 to 10, eleven times (each time in a new line). But the code is giving runtime error (segmentation fault). Can anybody please tell me where I am going wrong?
Thanks.
When you declare a vector of anything it doesn't have any elements yet.
Thus:
v[i].push_back(j)
is trying to insert j into a non-existent vector inside the vector v at position i.
In this case as you know the size you should initialize the vector with the number of elements you want in the constructor:
vector<vector<int> > v(11);
That initializes the vector v with 11 empty vectors inside it.
A segmentation fault occurs when you try to access memory that's not available. Generally when using vectors this means you're accessing an element that's outside of the vector (too high, or too low).
When you use a vector
always use the function size()
in your for loops
as it prevents it from overrunning. You're very likely accessing an element out of the vector size by going 0...10
(that'll return 11 elements, and it's uninitialised there anyway).
You aren't intialzing the first level of vectors.
for(i=0; i<11; i++)
vector<int> subVector;
v.push_back(subVector);
for(j=0; j<11; j++)
v[i].push_back(j);
v[i]
doesn't yet exist, your vector of vectors is empty.
Change it to vector< vector<int> > v(11);
to have an initial vector with 11 vectors in it.
When you create a new vector, it does not have elements by default. You have to insert the elements using push_back(). In your case, you did not enter any elements before in the vector, and you try to insert elements at ith position of that vector which is still not existent.
so you need to explicity define the size of the vector, i.e.
vector<vector<int> > v(10);
Now, vector know that there are 10 elements.
Hope, it helps.
Happy Coding!