ady
ady

Reputation: 37

C++ Segmentation fault while trying to create a vector of vectors

I want to create a vector of vectors in C++ with dimensions nx2 where n(rows) is given by user. I am trying to insert values in this vector using a for loop but As soon as give the value of n(rows), it gives a Segmentation fault error What to do?

#include <iostream>
#include <vector>
#include <cstdlib>
#define col 2
using namespace std;

int main()
{
    int row;
    cin >> row;
    vector<vector<int>> vec;

    for (int i = 0; i < row; ++i)
    {
        for (int j = 0; j < col; ++j)

            cin >> vec[i][j];
    }
    return 0;
}

Upvotes: 0

Views: 350

Answers (1)

selbie
selbie

Reputation: 104494

You need to resize a vector before inserting elements. Or use push_back to insert incrementally.

    vector<vector<int>> vec;
    vec.resize(row);
    
    for (int i = 0; i < row; ++i)
    {
        vec[i].resize(col);

        for (int j = 0; j < col; ++j)
        {
            cin >> vec[i][j];
        }
    }

OR:

    vector<vector<int>> vec;
    vec.resize(row);
    
    for (int i = 0; i < row; ++i)
    {

        for (int j = 0; j < col; ++j)
        {
            int value;
            cin >> value;
            vec[i].push_back(value);
        }
    }

Upvotes: 1

Related Questions