mardi 30 novembre 2021

Segmentation Fault while getting input from 2D vector

I get a segmentation fault when I run the code below.

int main()
{

    int R, C, val;
    cin>>R>>C;
    vector<vector<int>> a;
    for(int i = 0; i < R; i++)
    {
        for(int j = 0; j < C; j++)
        {
             cin>>val;
             a[i].push_back(val);
        }
    }

But when I change it to this, it seems to work. What is the reason?

int main()
{

    int R, C, val;
    cin>>R>>C;
    vector<vector<int>> a;
    for(int i = 0; i < R; i++)
    {
        vector<int>temp;
        for(int j = 0; j < C; j++)
        {
             cin>>val;
             temp.push_back(val);
        }
        a.push_back(temp);
    }

I get the same fault no matter what the value of R and C is kept.

Aucun commentaire:

Enregistrer un commentaire