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).
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With