Follow

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use
Contact

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 ?

MEDevel.com: Open-source for Healthcare and Education

Collecting and validating open-source software for healthcare, education, enterprise, development, medical imaging, medical records, and digital pathology.

Visit Medevel

>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;
}

Add a comment

Leave a Reply

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use

Discover more from Dev solutions

Subscribe now to keep reading and get access to the full archive.

Continue reading