Process returned -1073741819 (0xC0000005) in vectors

-1

I know that the vector is a dynamic array so you can enter values as you want. But in this code bellow the code crashes before I insert any value in the vector !! I don't know what I am doing wrong and I am new in programming. I tried to give it a size but it is not working.

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

    int main()
    {
         int H,W;
         cin >> H >> W;

         vector <vector <int>> A;

         for (int i = 0; i < H; i++)
         for (int j = 0; j < W; j++)
            cin >> A[i][j];
    

    return 0;
}
c++
vector
asked on Stack Overflow Nov 18, 2020 by Mohammad • edited Nov 18, 2020 by MikeCAT

1 Answer

4

You are reading values to A[i][j] while the vector A has no elements.

You have to allocate elements to read something there.

To allocate beforehand, you can use constructors.

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

int main()
{
    int H,W;
    cin >> H >> W;

    // allocate H W-element vectors
    vector <vector <int>> A(H, vector <int>(W));

    for (int i = 0; i < H; i++)
    for (int j = 0; j < W; j++)
        cin >> A[i][j];

    return 0;
}

Alternatively, you can insert elements via push_back().

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

int main()
{
    int H,W;
    cin >> H >> W;

    vector <vector <int>> A;

    for (int i = 0; i < H; i++)
    {
        vector <int> row;
        for (int j = 0; j < W; j++)
        {
            int value;
            cin >> value;
            row.push_back(value);
        }
        A.push_back(row);
    }

    return 0;
}
answered on Stack Overflow Nov 18, 2020 by MikeCAT • edited Nov 18, 2020 by MikeCAT

User contributions licensed under CC BY-SA 3.0