How to work with nested vectors in C ++?

I am trying to work with ints vectors to solve the sudoku puzzle that I am writing.

Question 1:

If I am going to access my 2d vector by index, do I need to initialize it with the appropriate size first?

For instance:

typedef vector<vector<int> > array2d_t;

void readAPuzzle(array2d_t grid)
{
    for(int i = 0; i < 9; i++)
        for(int j = 0; j < 9; j++)
            cin >> grid[i][j];
    return;
}

int main()
{
    array2d_t grid;
    readAPuzzle(grid);
}

An error will be triggered. I assume this is due to the fact that he is trying to access elites from a grid that have not yet been initialized?

I changed the grid declaration line:

array2d_t grid(9, vector<int>(9, 0));

And it seems to get rid of this error. Is this the right way to handle this?

Question 2:

Why does this happen when I try to read in my grid from cin and then print the grid, the grid is empty?

I am using the following code for this:

void printGrid(array2d_t grid)
{
    for (int i = 0; i < 9; i++)
    {
        for (int j = 0; j < 9; j++)
        {
            cout << grid[i][j] + " ";
        }
        cout << endl;
    }
}

void readAPuzzle(array2d_t grid)
{
    for(int i = 0; i < 9; i++)
        for(int j = 0; j < 9; j++)
            cin >> grid[i][j];

    return;
}

int main()
{
    array2d_t grid(9, vector<int>(9, 0));
    printGrid(grid);
    readAPuzzle(grid);
    printGrid(grid);
}

And I am trying to run my program as follows:

./a.out < sudoku-test

Where sudoku-test is a file containing the following:

3 0 0 0 0 0 0 0 0  
5 8 4 0 0 2 0 3 0  
0 6 0 8 3 0 0 7 5  
0 4 1 0 0 6 0 0 0  
7 9 0 0 2 0 0 5 1  
0 0 0 9 0 0 6 8 0  
9 3 0 0 1 5 0 4 0  
0 2 0 4 0 0 5 1 8  
0 0 0 0 0 0 0 0 6  

printGrid() , 9x9 0, . . .

- ?

+5
1

Q1: , . , 2D-. x + y * width.

Q2A: grid[i][j] + " " ( - int, ), ( ""), cout << grid[i][j] << " ".

Q2B: ( ) readAPuzzle. , . ( ):

void readAPuzzle(array2d_t& grid)
+5

All Articles