← Fundamentals
Fundamentals

C++ ranges and views

When does a view do its work, and what does it still refer to?

A C++ view describes a traversal whose work and storage lifetimes must be traced.

Outcome

Predict when and how often a view’s functions run, keep side effects out of them, tell a view that reads a live container from a copy, recognize a dangling result, and remove elements with std::erase_if.

Terminology (5)Terms used in this lesson

Term on the front, definition on the back. Paste with tabs between fields and a new line between cards, or import the download in Anki as Basic.

View
A range type satisfying the view concept. The shown adaptors defer element transformation or selection; a view may refer to storage or own a suitable range.
Range adaptor
An object such as std::views::transform or std::views::filter that turns one range into a view with |.
std::ranges::dangling
The placeholder used by relevant iterator/subrange-returning algorithms when an rvalue range is not a borrowed_range.
Erase-remove
Moving kept elements forward with remove_if, then erasing the leftover range; std::erase_if does both.
Side effect
A change a function makes beyond returning its result, such as counting or pushing into a vector.

A traversal can be a value

A range supplies positions for traversal. A view is a range designed for inexpensive movement and composition; transform and filter views describe how traversal computes or selects values. They do not by themselves materialize a result container.

A view can refer to an existing range or own suitable input, so inspect the actual adapted type. The input, retained iterators and captured references must remain valid for their use. Traversal can evaluate a transformation again, and a prepared view is not automatically a snapshot.

01Laziness

Building the delivery pipeline is not a delivery

The candle shop’s stock tool needs to add delivery lots, remove sold-out shelf records and reconcile an order file. A pipeline can look complete before it has touched the stock. The desk needs to know when its work happens, which container it reads and what the returned range actually represents.

Before changing the stock tool, isolate its delivery transform: it prints when it doubles a lot. The built marker separates pipeline construction from the later total. Which action starts the work?

main.cpp
Follow appearance
GitHub Light
GitHub Dark
Rosé Pine
Catppuccin Mocha
VS Code Dark+
#include <iostream>
#include <ranges>
#include <vector>

int main() {
    std::vector<int> lots{1, 2, 3};

    auto doubled = lots | std::views::transform([](int lot) {
                       std::cout << "transform " << lot << '\n';

                       return lot * 2;
                   });

    std::cout << "built\n";

    int total = 0;

    for (int lot : doubled) {
        total += lot;
    }

    std::cout << "total " << total << '\n';
}
What is printed first?
C++ · terminal.sh
Follow appearance
GitHub Light
GitHub Dark
Rosé Pine
Catppuccin Mocha
VS Code Dark+
clang++ -std=c++2c -Wall -Wextra -pedantic main.cpp -o main && ./main

Use the C++ workspace from the first reading and the declared clang++ command for each complete file. The counter traces are tied to the recorded compiler/library run; the iterator rules explain why view callbacks are unsuitable places for business bookkeeping.

02Reading twice

An accepted lot can be transformed again

A report may filter transformed quantities before totaling them. This probe counts transformations while retaining quantities above 10. Does composing the two views promise one transformation for each source record?

main.cpp
Follow appearance
GitHub Light
GitHub Dark
Rosé Pine
Catppuccin Mocha
VS Code Dark+
#include <iostream>
#include <ranges>
#include <vector>

int main() {
    std::vector<int> lots{1, 2, 3};
    int calls = 0;

    auto big = lots | std::views::transform([&calls](int lot) {
                   ++calls;

                   return lot * 10;
               }) |
               std::views::filter([](int lot) { return lot > 10; });

    int total = 0;

    for (int lot : big) {
        total += lot;
    }

    std::cout << "calls " << calls << ", total " << total << '\n';
}
Does this transform/filter pipeline promise one transform invocation per source element?
Loading A kept element is transformed again when read…

03What a result refers to

The input storage must outlive its iterator

The report may ask a helper for a vector of lots, then search that result. This reduced lookup keeps only found. What does that result allow after the statement ends?

main.cpp
Follow appearance
GitHub Light
GitHub Dark
Rosé Pine
Catppuccin Mocha
VS Code Dark+
#include <algorithm>
#include <iostream>
#include <vector>

std::vector<int> lots() {
    return {1, 2, 3};
}

int main() {
    auto found = std::ranges::find(lots(), 3);

    std::cout << *found << '\n';
}
What does the compiler do?

04Live, not a snapshot

A pending shelf view sees the correction

A shelf correction can arrive after a filter is prepared but before the list is read. The first lot changes to 5 before any begin call. Which lots will the pending filter show?

main.cpp
Follow appearance
GitHub Light
GitHub Dark
Rosé Pine
Catppuccin Mocha
VS Code Dark+
#include <iostream>
#include <ranges>
#include <vector>

int main() {
    std::vector<int> lots{1, 2, 3};
    auto big = lots | std::views::filter([](int lot) { return lot > 1; });

    lots[0] = 5;

    const char *separator = "";

    for (int lot : big) {
        std::cout << separator << lot;
        separator = " ";
    }

    std::cout << '\n';
}
What is printed?

05Repair the candle shop

Restock, clear sold-out scents, then report

The candle-shop package needs three repairs in separate supplied complete files. Add delivery lots to the retained stock, remove sold-out shelf records, then reconcile accepted orders and rejected physical lines.

This lab is C++-only. Each file contains its headers, reader and complete caller.

Repair the candle shop

Preserve delivery order, remove every empty shelf record, then keep report totals and rejected-line numbers consistent.

  1. easy · F-RANGES-V4-1 Restock the shelf
  2. medium · F-RANGES-V4-2 Clear sold-out scents
  3. hard · F-RANGES-V4-3 Report the orders
Sources

Report a problem in this lesson

For typos, mistakes and things that don’t work. We read every report and fix what’s wrong, but we don’t reply here, so a question won’t get an answer.