Code giving runtime error but runs on other compilers please help (C++)


#1
vector<vector<int> > Solution::generateMatrix(int A) {
    vector<vector<int>> ans;
    int val=1;
    if (A==0)
        return ans;
    for (int i=0; i<(A+1)/2; i++)
    {
        for (int j=i; j<A-i; j++)
        {
            ans[i][j]=val;
            val++;
        }
        for (int j=i+1; j<=A-1-i; j++)
        {
            ans[j][A-1-i]=val;
            val++;
        }
        for (int j=A-2-i; j>=i; j--)
        {
            ans[A-1-i][j]=val;
            val++;
        }
        for(int j=A-2-i; j>i; j--)
        {
            ans[j][i]=val;
            val++;
        }
    }
    return ans;
}

#2

You need to declare the vector of size A*A before accessing that location with ans[i][j].
You could do that either by first putting each row in a separate vector and pushing that vector into the 2d vector or initialising straightaway–

vector<vector<int>>(A,vector<int>(A))


#3

vector<vector<int> > ans(A,vector<int>(A,0));
Add this where you declare your vector, it will work just fine