Search code examples
c++stdvector

Why am I unable to read 2D array using vectors?


The code is :

#include<iostream>
#include<vector>
using namespace std;

int main()
{
    vector<vector<int>> arr;

    int i, j;

    for (i = 0; i < 5; i++)
    {
        for (j = 0; j < 5; j++)
        {
            cin >> arr[i][j];
        }
    }

    return 0;

}

Compilation is successful. But, when I tried to run the code in Visual Studio (2013) I got runtime error "vector subscript out of range".

Why am I getting this run time error ? Is this the correct way to read 2D array input from user ?


Solution

  • Because the vector arr is empty in your code.

    #include<iostream>
    #include<vector>
    using namespace std;
    
    int main()
    {
        vector<vector<int>> arr;
        cout << arr.size() << endl;       // output: 0
        cout << arr.empty() << endl;      // output: 1 , it means arr is empty
    
        // First way
        vector<vector<int>> arr1(5, vector<int>(5));
        
        int i, j;
    
        // Second way
        arr.resize(5);
        for (i = 0; i < 5; i++) {
            for (j = 0; j < 5; j++) {
                int temp;
                cin >> temp;
                arr[i].emplace_back(temp);
            }
        }
    
        return 0;
    }