Reputation: 53
#include <iostream>
#include <vector>
using namespace std;
int m,n;
vector<vector<int> > name(m,vector<int>(n));
int main()
{
cin>>m>>n;
for ( int i=0;i<m;i++)
{
for( int j=0;j<n;j++)
cin>>name[i][j];
}
}
Every time I give the input m
and n
, it crashes! What I am trying to do is to give the input to a 2 dimensional array of m
rows and n
columns.
Upvotes: 0
Views: 106
Reputation: 517
Error is you are trying to access the index out of bound
Because your name is not a 2D vector.
use this code instead to make name
a 2D vector.
vector < vector <int> > name;
vector<int > col;
int r, c;
void main()
{
cin >> r;
cin >> c;
for (int i = 0; i < c; i++)
{
col.push_back(i);//push i to col just to make it size of columns needed
}
for (int i = 0; i < r; i++)
{
name.push_back(col);//pushing vector col of size c into name to
//make it a 2D vecotr
}
//now name is a 2D vector with r rows of each c column
cout << "\nNow Enter values";
for (int i = 0; i < r; i++)
{
for (int j = 0; j < c; j++)
{
cin >> name[i][j];//input values
}
}
getch();
}
Upvotes: 1
Reputation: 3645
Because of you have run out of bounds.
The name
vector is global variable, so it is initialised at the moment of program starting, even before main
function. Also integer global variables are initialised with 0
in C++. So the name
vector has zero size.
After reading n
and m
values you need to resize the vector.
Upvotes: 5
Reputation: 103693
You need to initialize your vector (or resize it) after you read the values for m
and n
. As you have it, m
and n
are 0* when the vector is initialized, so the size of the vector is 0.
*this is only the case because you placed them at global scope. if placed in a function, they would be uninitialized, and it would be undefined behavior to use their values
Upvotes: 5