Learning pathOriginal reference
Lesson 5 of 12

Vectors in functions and grids

Choose copies or references deliberately and traverse nested vectors without assuming every row matches.

The vector knows its own size

A vector parameter carries a size() operation. A helper usually does not need a separate n unless it intentionally uses only a prefix. const std::vector<int>& reads the original, std::vector<int>& can modify it, and std::vector<int> receives an independent value.

Passing an existing n-element vector by value usually copies its elements, costing O(n) work and storage. A helper called q times to ask only for size can accidentally incur O(qn) copy work. A const reference avoids that copy but not any scan in the helper body.

Copies can be part of a correct plan

To print sorted values while preserving their original order, copy the vector, then sort the copy. Both sequences stay alive, so the extra copy needs linear storage. A returned local vector can safely be returned by value; C++ can elide or move that result.

Do not return a reference to a local vector after its lifetime ends. Vector equality compares matching contents, not object identity. Lexicographic order compares the first differing element, with the shorter equal prefix first.

Each nested row is a separate vector

vector<vector<int>> grid(rows, vector<int>(cols)) creates independent rows with cols zero-valued cells each. grid[i][j] requires both a valid row and a valid index within that row. The rows need not share one contiguous rectangular integer block.

Use auto& row and int& x when reading into the stored grid. Without the outer reference, input modifies a copied row. Ragged vectors may have different row lengths, including empty rows, so traverse each row’s own size. With r rows and m total cells, logical storage is O(r + m); row objects still exist when rows are empty.

C++23
// Complete C++23 program. No input; output: 11 9 0
#include <iostream>
#include <vector>
int main() {
    std::vector<std::vector<int>> groups{{4, 7}, {9}, {}};
    for (int i = 0; i < static_cast<int>(groups.size()); ++i) {
        long long total = 0;
        for (int x : groups[i]) total += x;
        if (i != 0) std::cout << ' ';
        std::cout << total;
    }
    std::cout << '\n';
}

Container workbench

Insert values, then remove the next accessible item. Priority queue values are shown sorted for explanation, not as an internal heap.

80
31
52

Next removal: 5. Size: 3.

Guided simulation · Change the inputs to test your understanding.

Pause & predict

What does for (auto row : grid) do differently from for (auto& row : grid)?

Choose an answer
Try it yourself

Turn the idea into code

Read positive rows and cols, each at most 300, then a matrix with values in [−10⁹, 10⁹]. Store it as a nested vector and print column sums from left to right.

Give me a hint

For each column, reset one long long total, then visit that column in every row.

Show the explained solution

The inner loop visits exactly the requested column. Repeating across all columns visits every cell once, giving O(rows × cols) processing time and stored cells. Wide totals handle sums exceeding int.

C++23
// Complete C++23 program. Input: rows cols, then the matrix row by row.
#include <iostream>
#include <vector>
int main() {
    int rows = 0, cols = 0;
    std::cin >> rows >> cols;
    std::vector<std::vector<int>> grid(rows, std::vector<int>(cols));
    for (auto& row : grid) {
        for (int& x : row) std::cin >> x;
    }
    for (int col = 0; col < cols; ++col) {
        long long total = 0;
        for (int row = 0; row < rows; ++row) total += grid[row][col];
        if (col != 0) std::cout << ' ';
        std::cout << total;
    }
    std::cout << '\n';
}

Your notes

Ready for the next idea?

Mark complete when you can explain it yourself.

From a problem to a programIdentify the input, output, and constraints, then translate a small plan into C++.Variables, types, and remembered valuesChoose a representation, initialize it, and understand what assignment really changes.Arithmetic without surprisesPredict division and remainder, widen before multiplication, and format decimal answers.Conditions and logical decisionsBuild exclusive categories, combine comparisons, and protect operations with short-circuit logic.Optional: other ways to chooseRecognize switch for exact choices and the conditional operator for choosing a value.For loops: make repetition preciseTrace initialization, condition, body, and update—and avoid an extra iteration.While, do-while, and stopping rulesChoose a loop from its stopping condition and read the exact input format.Break, continue, and early answersDistinguish leaving a loop from skipping one iteration, without losing required input.Five patterns worth understandingUse sums, counts, best-so-far candidates, products, and flags to process a stream.Nested loops: rows and columnsTranslate a shape into two loop roles and count the total work.Take a number apart, one digit at a timeUse remainder and division to process decimal digits, including zero.Multiple cases and a debugging mindsetCombine the patterns, isolate each case, and test the boundaries that can break your idea.Arrays: give every value a placeUnderstand indices, initialization, capacity, active length, and the first safe array loop.Scan, count, search, and compareDistinguish values from positions and preserve the exact tie rule a problem asks for.Change a sequence without losing itUpdate, copy, compare, reverse, and inspect neighbours using the correct bounds.Matrices: think in two coordinatesTraverse tables, total rows and columns, inspect diagonals, and protect grid neighbours.Characters become stringsSeparate characters from numbers, then safely inspect and edit managed text.Read the text the problem actually givesChoose words or full lines, preserve empty cases, and reset only the state that needs it.Scan text: count, filter, transformBuild a result from matching characters without losing leading zeros or skipping shifted text.Join, compare, and find textLearn content comparison, lexicographical order, substring counts, and the not-found sentinel.