A stockroom can have several shelves, each with several bins. A single list loses that grouping. A nested vector keeps a vector for each row, making a table of values.
In std::vector<std::vector<int>>, the outer vector's elements are themselves std::vector<int> values. Read the type from the inside out: integers make a row; rows make the table. The adjacent >> characters close the two type descriptions.
#include <vector>
#include <iostream>
int main() {
std::vector<std::vector<int>> seats{{2, 3}, {4, 6}};
std::cout << seats[1][0] << '\n';
int total = 0;
for (std::vector<int> row : seats) {
for (int count : row) {
total += count;
}
}
std::cout << total << '\n';
}
The example prints 4 and 15. The first bracket selects a row; the second selects a value within that row. Both indices start at zero. The braces around each row show which integers belong together.
For variable indices, validate the row first using rowIndex < table.size(). Only then can you check columnIndex < table[rowIndex].size(). Different rows may have different lengths, or even be empty. Do not assume that one row's length describes every other row.
The outer range loop above copies one row at a time. The inner loop copies its integers. That is safe and simple for these tiny tables; a later lesson introduces read-only references to avoid larger copies. Neither loop changes the original table.
The starter has two rows of three values. For the first task, locate the row before counting across to the column; both counts start at zero. For the total, use the innermost TODO: that body runs once per bin. Adding there includes every bin, whereas adding only in the outer body would happen once per row.
Follow the two selections in this separate table: first choose a whole row, then choose one position within that row.
Here table[1][2] selects 12. The starter's shelves has the same row-and-column selection rule but different values, so use its own contents when checking your result.
selected from row index 1, column index 2 of shelves. Expect Selected: 6.units value in total inside the inner loop. Expect Table total: 27.Edit main.cpp, then select Run to inspect the Console. Select Submit to check your completed tasks.