Thuta Learning
C++
AdvancedProgrammingBeginner

Algorithms, Ranges & Lambdas

C++Lesson 2835 min

What you'll walk away with

  • Use std::ranges algorithms such as sort, count_if, find_if and for_each, including projections
  • Write lambdas and choose between capturing by value and by reference
  • Build lazy pipelines with std::views::filter, transform and take, and explain when they run
  • Spot dangling captures, dangling views and invalid comparators before they become undefined behaviour

Explain it simply

Algorithms, lambdas and ranges in plain language

Most loops you write do one of a handful of jobs: find something, count something, sort, transform each item, add everything up. The standard library already has a tested, named function for each of these jobs in <algorithm> and <numeric>. Calling std::ranges::count_if states your intent in one line, where a loop makes the reader reverse-engineer it.

A lambda is a small unnamed function you write right where you need it, such as the rule 'is this order large?'. A view is a recipe for a sequence: 'the customer names of the large orders'. Nothing is computed until you actually walk through it.

Problem → Why → Solution

The problem: three loops, two temporary vectors, one bug

A report needs the customer names of orders of 100 or more, sorted by total. The first version is three loops, two temporary vectors and a hand-written bubble sort. The bug is in a loop bound: <= instead of <, which reads one element past the end. It is the kind of bug that passes on your machine and crashes in production.

report_loops.cpp
std::vector<Order> large;
for (std::size_t i = 0; i <= orders.size(); ++i) {      // <= reads past the end
    if (orders[i].total >= 100) large.push_back(orders[i]);
}
for (std::size_t i = 0; i < large.size(); ++i) {        // hand-written bubble sort
    for (std::size_t j = 0; j + 1 < large.size() - i; ++j) {
        if (large[j].total > large[j + 1].total) std::swap(large[j], large[j + 1]);
    }
}
std::vector<std::string> names;
for (const Order& o : large) names.push_back(o.customer);

Why loops like these go wrong

Every hand-written loop is a small program with its own bounds, its own index variable and its own chance to be wrong. The intent, 'names of large orders, by total', is buried under the mechanics. Standard algorithms have no index to get wrong, they name the intent, and they have been tested by countless C++ programmers. Ranges and views go one step further and remove the temporary vectors too.

Core concept: the verb, the rule and the recipe

Classic algorithms take a pair of iterators: std::sort(v.begin(), v.end()). The C++20 std::ranges versions take the container directly and also accept a projection: std::ranges::sort(orders, {}, &Order::total) sorts by total, where {} means the default comparison, std::ranges::less. sort needs random-access iterators, so it works on vector, array and deque but not on std::list. The comparator must be a strict weak ordering: use <, never <=.

A lambda looks like [captures](parameters) { body }, and its return type is usually deduced. A lambda is an object: [x] copies x when the lambda is created and keeps the copy inside, so later changes to x are not seen. [&x] refers to the variable itself, so x must stay alive for as long as the lambda is used. Add mutable if the lambda needs to change its own copy.

CaptureMeaningSafe when
[threshold]a copy taken at creationalways; the lambda owns its copy
[&sum]a reference to sumthe lambda runs while sum is alive
[=] / [&]everything used, by copy / by referenceshort lambdas called on the spot
[this]the current objectthe object outlives the lambda

Views from <ranges> (std::views::filter, transform, take, reverse) are chained with |. A view does not own elements and computes nothing when it is created; it is lazy: each element is produced when the loop asks for it, and only as many as are asked for. A view refers to the underlying container, so the container must outlive the view.

Pick an algorithm when you need a result now, such as a sort or a count. Pick a view to describe a sequence you will walk once, without building a temporary vector. In C++20 you turn a view into a vector with a loop and push_back; C++23 adds std::ranges::to for that.

Algorithm = verb, lambda = rule, view = recipe
  1. Pick the verb: sort, count_if, find_if
  2. Pass the rule as a lambda
  3. Chain views to describe a sequence
  4. Values are computed as you iterate

A view and a reference-capturing lambda both point at data they do not own, so that data must outlive them.

General pattern

cpp
std::ranges::sort(range);                          // default <
std::ranges::sort(range, comp, &Type::member);     // comparator + projection
auto n = std::ranges::count_if(range, predicate);
auto it = std::ranges::find_if(range, predicate);  // range.end() if none

auto rule = [capture](const Type& x) { return expression; };

auto view = range | std::views::filter(predicate)
                  | std::views::transform(function)
                  | std::views::take(n);
for (auto&& value : view) { /* computed here */ }

An algorithm takes a whole range, optionally with a comparator and a projection. A lambda carries the rule, and a view pipeline produces elements only when the loop asks for them.

Worked example: an order report

This is the report from the problem section rewritten with algorithms: no index variables, no hand-written sort, no temporary vectors. Notice that the rule isLarge is written once and reused by both count_if and the filter view.

order_report.cpp
#include <algorithm>
#include <iostream>
#include <ranges>
#include <string>
#include <vector>

struct Order {
    std::string customer;
    int total;
};

int main() {
    std::vector<Order> orders{{"Aye", 120}, {"Ko", 45}, {"Su", 300}, {"Min", 80}};

    std::ranges::sort(orders, {}, &Order::total);    // sort by total, ascending
    for (const Order& o : orders) std::cout << o.customer << ' ';
    std::cout << '\n';

    int threshold = 100;
    auto isLarge = [threshold](const Order& o) { return o.total >= threshold; };
    std::cout << "large orders: " << std::ranges::count_if(orders, isLarge) << '\n';

    auto largeNames = orders | std::views::filter(isLarge)
                             | std::views::transform(&Order::customer);
    for (const std::string& name : largeNames) std::cout << name << ' ';
    std::cout << '\n';

    int sum = 0;
    std::ranges::for_each(orders, [&sum](const Order& o) { sum += o.total; });
    std::cout << "sum: " << sum << '\n';
}

Code breakdown

  1. Sort by a memberstd::ranges::sort(orders, {}, &Order::total);

    {} is the default comparator (<) and &Order::total is the projection, so orders are compared by their total rather than as whole objects. No comparator lambda is needed.

  2. Capture by valueauto isLarge = [threshold](const Order& o) { return o.total >= threshold; };

    [threshold] copies the value 100 when the lambda is created. Changing threshold later would not affect isLarge, and the lambda is safe to pass anywhere.

  3. Count with the same rulestd::ranges::count_if(orders, isLarge)

    count_if calls the lambda on every element and returns how many said true: 2 (the orders of 120 and 300).

  4. A lazy pipelineauto largeNames = orders | std::views::filter(isLarge)

    This line computes nothing; it only builds the recipe 'large orders, mapped to customer names'. filter and transform run when the following for loop asks for elements.

  5. Capture by reference to accumulatestd::ranges::for_each(orders, [&sum](const Order& o) { sum += o.total; });

    The lambda must change sum, so it captures it by reference with [&sum]. That is safe here because for_each runs immediately, while sum is still alive.

You should see
Ko Min Aye Su
large orders: 2
Aye Su
sum: 545

Seeing laziness with your own eyes

The transform lambda below prints a message every time it computes a value. The vector holds six numbers, but the pipeline ends in take(2), so only two are computed, and only while the loop runs, not when the view is built.

lazy_views.cpp
#include <iostream>
#include <ranges>
#include <vector>

int main() {
    std::vector<int> numbers{1, 2, 3, 4, 5, 6};

    auto squares = numbers
        | std::views::transform([](int n) {
              std::cout << "(computing " << n << ") ";
              return n * n;
          })
        | std::views::take(2);
    std::cout << "view built, nothing computed yet\n";

    for (int s : squares) std::cout << s << '\n';
}

The output is "view built, nothing computed yet", then "(computing 1) 1" and "(computing 2) 4". Looping over squares a second time would run the lambda again, because a view does not store its results. If expensive values are needed twice, store them in a vector once.

In real projects

Algorithms and lambdas in real projects

In modern C++ codebases, algorithm calls outnumber hand-written loops, and "isn't this just std::ranges::any_of?" is a common code-review comment:

  • Data processing: filter log lines by level, transform them into messages and take the first 50, all in one view pipeline with no temporary copies.
  • UI tables: when the user clicks a column header, sort with a projection, as in std::ranges::sort(rows, {}, &Row::price).
  • Callbacks and event handlers: buttons, timers and network replies store lambdas and call them later. Capture lifetime matters most here; a callback that captured [this] and fires after its object is destroyed is undefined behaviour and often crashes.
  • Performance: since C++17 most classic algorithms accept an execution policy such as std::execution::par, so a loop can run in parallel without being rewritten.

Common mistakes

Common mistakes with algorithms, lambdas and ranges

Both bugs below compile without a warning at GCC's default optimisation level, even with -Wall -Wextra:

dangling.cpp
auto makeAdder(int amount) {
    return [&amount](int x) { return x + amount; };   // reference to a parameter
}

auto evenNumbers() {
    std::vector<int> local{1, 2, 3, 4, 5, 6};
    return local | std::views::filter([](int n) { return n % 2 == 0; });
}   // local is destroyed here, but the view still points at it

Capturing by reference something that will die

amount dies when makeAdder returns, yet the returned lambda still refers to it, so calling it later is undefined behaviour. When a lambda outlives the scope that created it, capture by value: [amount].

Returning a view over a local container

A view owns nothing, so when evenNumbers returns, local is destroyed and the view dangles. Return the container itself, or take the data by reference from a caller who owns it and build the view on that.

Using <= in a comparator

[](int a, int b) { return a <= b; } is not a strict weak ordering, since two equal elements each compare 'less' than the other. Passing it to sort is undefined behaviour and can read out of bounds or crash on inputs with many equal values. Use <, or a standard comparator such as std::ranges::greater{}.

Expecting a view to cache its results

A transform view calls its function again on every pass. If the lambda has side effects or does heavy work, looping twice means running it twice. Store the results in a vector when you need them more than once.

Mini challenge

Mini challenge: a word toolkit

Analyse a word list with algorithms, lambdas and views instead of hand-written index loops. Count the words at least minLength long, sort a copy by length (alphabetically on ties), print the first three long words in uppercase, and find the first word that starts with 'b'.

  • Use one isLong lambda that captures minLength, both in count_if and in a filter view
  • Sort a copy with std::ranges::sort and a lambda comparator, leaving the original vector unchanged
  • Use one view pipeline with filter, transform and take(3)
  • Check the result of std::ranges::find_if against end() before dereferencing it
word_toolkit.cpp
#include <algorithm>
#include <cctype>
#include <iostream>
#include <ranges>
#include <string>
#include <vector>

std::string toUpper(std::string word) {
    // TODO: uppercase every character (std::ranges::transform + std::toupper)
    return word;
}

int main() {
    std::vector<std::string> words{"pear", "fig", "banana", "kiwi", "apricot", "plum"};
    std::size_t minLength = 4;

    // TODO: isLong lambda capturing minLength; print how many words are long
    // TODO: sort a copy by length, then alphabetically; print it
    // TODO: filter | transform(toUpper) | take(3); print the result
    // TODO: find_if the first word starting with 'b'; check before printing
}

Expected: It prints long words: 5, then fig kiwi pear plum banana apricot, then PEAR BANANA KIWI, then first b-word: banana and original first: pear, which proves the original vector was not changed.

Show hint

In the comparator, return a.size() < b.size() when the sizes differ and a < b otherwise; both are strict. Call std::toupper with an unsigned char and static_cast the result back to char. w.starts_with('b') is available since C++20.

Show solution
word_toolkit.cpp
#include <algorithm>
#include <cctype>
#include <iostream>
#include <ranges>
#include <string>
#include <vector>

std::string toUpper(std::string word) {
    std::ranges::transform(word, word.begin(), [](unsigned char c) {
        return static_cast<char>(std::toupper(c));
    });
    return word;
}

int main() {
    std::vector<std::string> words{"pear", "fig", "banana", "kiwi", "apricot", "plum"};
    std::size_t minLength = 4;

    auto isLong = [minLength](const std::string& w) { return w.size() >= minLength; };
    std::cout << "long words: " << std::ranges::count_if(words, isLong) << '\n';

    std::vector<std::string> sorted = words;     // sort a copy, keep the original
    std::ranges::sort(sorted, [](const std::string& a, const std::string& b) {
        if (a.size() != b.size()) return a.size() < b.size();
        return a < b;                            // same length: alphabetical
    });
    for (const std::string& w : sorted) std::cout << w << ' ';
    std::cout << '\n';

    for (const std::string& w : words | std::views::filter(isLong)
                                      | std::views::transform(toUpper)
                                      | std::views::take(3)) {
        std::cout << w << ' ';
    }
    std::cout << '\n';

    auto it = std::ranges::find_if(words, [](const std::string& w) {
        return w.starts_with('b');
    });
    if (it != words.end()) std::cout << "first b-word: " << *it << '\n';
    std::cout << "original first: " << words.front() << '\n';
}

Quick quiz 1 / 3

What does int base = 10; auto addBase = [base](int x) { return x + base; }; base = 100; std::cout << addBase(1); print?

Quick quiz 2 / 3

Which comparator is valid for std::ranges::sort(v, comp) and does not cause undefined behaviour?

Quick quiz 3 / 3

In lazy_views.cpp from the deeper section, after looping over squares once, how many times has the transform lambda run?

What to remember

  • std::ranges algorithms take the container directly, and a projection lets them sort, find or count by one member.
  • In a lambda, [x] is a copy made at creation and [&x] is the variable itself; capture by value when the lambda outlives the scope.
  • Views are lazy and own no data: they compute while you iterate, and the underlying container must outlive them.
  • Comparators must be strict weak orderings: use < or >, never <=.

The Current ISO C++ Standard (C++23) — Standard C++ Foundation

Updated on

Progress is saved only in this browser on this device. It isn't synced to other devices.

Report a problem with this lessonOpens your email app with this lesson's address filled in — nothing is sent until you send it.

Algorithms, Ranges & Lambdas | Thuta Learning