bhylu.com

Advertisements

C++ Ranges and Views

Filter and transform a live source without assuming a view owns a copied result.

How it works

Ranges views can describe lazy operations such as selecting valid loads and doubling each selected value. Many views borrow their source rather than owning an independent result. Evaluation happens during traversal, so changes to the source or stateful predicates can affect results. Keep owners alive and avoid invalidating mutations while a view is in use. Materialize a vector when you need a stable snapshot or ownership independent of the source.

Run it locally

Use a C++20 compiler and matching standard library in a separate lab folder. The command uses c++; substitute g++, clang++ or zig c++ for your toolchain. C++ does not currently run in Bhylu’s browser playground. Apache, PHP and MySQL are not needed.

c++ -std=c++20 -Wall -Wextra -Wpedantic -Werror ranges-views.cpp -o lesson

On Windows use -o lesson.exe and run .\lesson.exe in PowerShell. On Unix-like systems run ./lesson. Thread examples may need -pthread on your platform.

Download the complete C++ source. Run file labs in a private empty directory, away from existing reports.

Example

C++20 · ranges-views.cpp

#include <iostream>
#include <vector>
#include <ranges>

int main() {
    std::vector<int> loads{2, -1, 4, 0};
    auto planned = loads | std::views::filter([](int value) { return value > 0; })
                         | std::views::transform([](int value) { return value * 2; });
    for (int value : planned) { std::cout << value << ' ' ; }
    std::cout << '\n';
}

Expected result

4 8 

The negative and zero entries are skipped under this chosen policy. The two positive values are transformed on demand, not written back into loads. The fixture keeps multiplication safely bounded. C++20 does not include every later range conversion convenience, so build a destination with a deliberate traversal when a concrete owned collection is required.

Consult the WG21 C++ working group and the C++ Core Guidelines for language references and design guidance. Check the selected standard version and your implementation’s library support.