Nafeeur Rahman
Nafeeur Rahman

Reputation: 67

Initialization 2D Vector in C++

I want to take input from user for a 2D matrix by 2D vector. But while I'm doing like below, program crashed!!! But why?

int m, n;
cin>>m>>n;

vector<vector<int> > v;

for(int i=0; i<m; i++)
{
     for(int j=0; j<n; j++)
     {
         int a;
         cin>>a;
         v[i].push_back(a);
     }
}

What will be the solution according to my code.

Upvotes: 0

Views: 1312

Answers (3)

G.Monkee
G.Monkee

Reputation: 1

v[i] hasn't been constructed when you call v[i].push_back(),you just need to init v first.it's simple:

vector<vector<int>> v;
v.reserve(m);
for(...)
...

Upvotes: -1

songyuanyao
songyuanyao

Reputation: 172864

At the point where v[i].push_back(a); is called inside the for loop, vector v is empty and using v[i] will lead to undefined behaviour.

Your code should first push_back a vector<int>:

for (int i=0; i<m; i++)
{
    v.push_back(vector<int>());
    for (int j=0; j<n; j++)
    {
        int a;
        cin >> a;
        v[i].push_back(a);
    }
}

An alternative would be to initialize vector v explicitly to size m:

int m, n;
cin>>m>>n;
vector<vector<int> > v(m);

for(int i=0; i<m; i++)
{
     for(int j=0; j<n; j++)
     {
         int a;
         cin>>a;
         v[i].push_back(a);
     }
}

Upvotes: 6

steiner
steiner

Reputation: 170

Since you know the size of your matrix just resize v before you fill it :

vector<vector<int> > v(m);
for(int i=0; i<m; i++)
{
    v[i].resize(n);
    for(int j=0; j<n; j++)
    {
        cin >> v[i][j];
    }
}

Upvotes: 4

Related Questions