Skip to content

Read Collections by const Reference

The Course
•
35 min study

A function that totals a list of durations only needs to look at the list. If you pass a std::vector<int> the way you passed an int on Day 3, by value, C++ copies every element into a new vector for each call. With three elements nobody notices. With a hundred tasks, each holding a title string, every report would copy every title just to read it. And if the helper accidentally changed an element, the change would vanish with the copy, hiding the bug.

C++ gives you three ways to pass a collection, and the parameter type tells every reader what the function intends to do:

  • std::vector<int> values copies the vector. The function gets its own independent version.
  • std::vector<int>& values refers to the caller's vector. The function can change it.
  • const std::vector<int>& values refers to the caller's vector without copying it, and the compiler forbids changing it through that name.

Predict and run

Predict before running C++
#include <iostream>
#include <vector>

int total(const std::vector<int>& values) {
    int sum = 0;
    for (int value : values) {
        sum += value;
    }
    return sum;
}

int main() {
    std::vector<int> minutes{25, 10, 15};
    std::cout << total(minutes) << " " << total({}) << "\n";
    return 0;
}
Check your prediction
Text
50 0

An empty vector works naturally: the loop visits no elements and the sum stays 0. The call total({}) also shows a useful property of const references: they can refer to a temporary vector built right at the call. A non-const reference cannot, because changing a temporary that disappears at the end of the statement would be pointless.

Copy, reference and const reference side by side

Three parameter types C++
#include <iostream>
#include <vector>

void add_by_value(std::vector<int> values) {
    values.push_back(99);
}

void add_by_reference(std::vector<int>& values) {
    values.push_back(99);
}

int count(const std::vector<int>& values) {
    return static_cast<int>(values.size());
}

int main() {
    std::vector<int> plan{25, 10};
    add_by_value(plan);
    std::cout << count(plan) << "\n";
    add_by_reference(plan);
    std::cout << count(plan) << "\n";
    return 0;
}
Text
2
3

add_by_value appended to its private copy, which was destroyed at the end of the call, so plan still had two elements. add_by_reference appended to plan itself. count only reads, so it takes a const reference: no copy, and no way to change plan by accident. static_cast<int> converts the unsigned size to an int explicitly, which keeps the warning settings quiet and shows the reader that the conversion is intended.

What const actually protects

Inside count, a line such as values[0] = 0; or values.push_back(1); does not compile:

Shell
main.cpp:13:15: error: cannot assign to return value because function 'operator[]' returns a const value

This is const-correctness: the promise "this function only reads" is checked by the compiler, not just written in a comment. The promise is about this function's view of the vector. It does not freeze the caller's vector; main can still change plan freely before and after the call.

A useful default follows from this. For a parameter you only read, take small values like int by value and larger objects like vectors and strings by const reference. Use a plain reference only when changing the caller's object is the purpose of the function.

Change every element through a reference loop

The range-based loop has the same choice. for (int value : values) gives you a copy of each element. To change the elements themselves, the loop variable must be a reference:

Update elements in place C++
#include <iostream>
#include <vector>

void add_to_all(std::vector<int>& values, int extra) {
    for (int& value : values) {
        value += extra;
    }
}

int main() {
    std::vector<int> plan{25, 10, 40};
    add_to_all(plan, 5);
    for (int value : plan) {
        std::cout << value << " ";
    }
    std::cout << "\n";
    return 0;
}
Text
30 15 45 

Remove the & from int& value and the vector prints unchanged, because each value would be a copy that is discarded at the end of its iteration. Note that the output ends with a space before the newline, since the loop prints one after every value.

Practice

Exercise

Your turn

Write two functions:

  • int count_at_least(const std::vector<int>& values, int limit) returns how many values are at least limit.
  • void add_to_all(std::vector<int>& values, int extra) adds extra to every element.

Starting from 25, 10 and 40, print Before: 2 for a limit of 15, add 5 to every value, then print After: 3. Finally print Empty: 0 by calling count_at_least with an empty vector.

Your workspace C++
#include <iostream>
#include <vector>

int main() {
    std::vector<int> plan{25, 10, 40};
    // Write both functions above main, then call them here.
    return 0;
}
Hint 1: the idea

The counting function only reads, so it takes a const reference. The adding function changes the caller's elements, so both its parameter and its loop variable must be references.

Hint 2: a first step

In count_at_least, start a counter at 0 and loop with for (int value : values), increasing it when value >= limit.

Show one solution
Run the solution C++
#include <iostream>
#include <vector>

int count_at_least(const std::vector<int>& values, int limit) {
    int count = 0;
    for (int value : values) {
        if (value >= limit) {
            ++count;
        }
    }
    return count;
}

void add_to_all(std::vector<int>& values, int extra) {
    for (int& value : values) {
        value += extra;
    }
}

int main() {
    std::vector<int> plan{25, 10, 40};
    std::cout << "Before: " << count_at_least(plan, 15) << "\n";
    add_to_all(plan, 5);
    std::cout << "After: " << count_at_least(plan, 15) << "\n";
    std::cout << "Empty: " << count_at_least({}, 15) << "\n";
    return 0;
}
Text
Before: 2
After: 3
Empty: 0

The signatures alone tell the story: count_at_least cannot change the plan, and add_to_all exists to change it. The 10 became 15, which is exactly the limit, so the after count includes it only because the comparison is >=. In the checkpoint you will write a collection function whose trickiest case is the empty vector.

Was this article helpful?

Your response is saved on this device.