Two-Dimensional Vectors

The Two-Dimensional Arrays lesson stored a table with a fixed number of rows and columns. A vector can hold any type of value, even other vectors. A vector of vectors is a table where each row is a vector<int>. Like any vector, it can be sized while the program runs.

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

int main() {
    vector<vector<int>> grid = {
        {1, 2, 3},
        {4, 5, 6}
    };
    cout << grid[1][2] << "\n";
    cout << grid.size() << "\n";
    cout << grid[0].size() << "\n";
    return 0;
}

Output:

6
2
3

Read vector<vector<int>> from the inside out: a vector whose values are vector<int>. grid[1] is the second row, which is itself a vector. grid[1][2] is the third value of that row, 6. As with arrays, the row index comes first.

grid.size() is the number of rows, 2. grid[0].size() is the length of the first row, 3, which is the number of columns.

A grid of a given size

Often you know the size only when the program runs, for example from input. First, a vector of one row. vector<int> row(4, 0) makes a vector with 4 values, each 0:

vector<int> row(4, 0);
cout << row.size() << " " << row[3] << "\n";

Output:

4 0

A grid is the same idea one level up. Give the number of rows, and the row to copy into each place:

int rows = 2;
int cols = 4;
vector<vector<int>> grid(rows, vector<int>(cols, 0));
grid[0][1] = 7;

for (int r = 0; r < rows; r++) {
    for (int c = 0; c < cols; c++) {
        cout << grid[r][c] << " ";
    }
    cout << "\n";
}

Output:

0 7 0 0 
0 0 0 0

vector<int>(cols, 0) is one row of 4 zeros. The grid holds 2 copies of it, so every row is its own vector. Changing grid[0][1] changed only the first row.

A grid must have its size before you use an index. This line makes an empty grid, with no rows at all:

vector<vector<int>> grid;
grid[1][2] = 5;

grid[1] does not exist, and C++ does not check the index. When we ran it, the program crashed with Segmentation fault. Give the size when you make the grid, or add rows with push_back.

Rows of different lengths

Each row is a separate vector, so the rows do not need the same length. This program builds a triangle with push_back, one row at a time:

vector<vector<int>> triangle;
for (int i = 1; i <= 3; i++) {
    vector<int> row;
    for (int j = 1; j <= i; j++) {
        row.push_back(j);
    }
    triangle.push_back(row);
}

for (const vector<int>& row : triangle) {
    for (int n : row) {
        cout << n << " ";
    }
    cout << "\n";
}

Output:

1 
1 2 
1 2 3

To print it, two range-based for loops are nested. The outer one gives each row, and the inner one gives each number in that row. Because the rows have different lengths, this is easier than index loops. The outer loop uses const vector<int>&, from the Vectors and Functions lesson, so that each row is read without being copied.

In the exercise, make a grid with the number of rows and columns from the input, fill it, and print the sum of each column.