Skip to content

Predicates and Captures

The Course
•
35 min study

The last lesson removed short tasks with a function is_short that hard-coded "below 15". The moment a report needs "below 30" or "at least the threshold the user typed", a fixed function stops working, and writing is_short_15, is_short_30 and so on is clearly wrong. What you need is a function that carries a value chosen at run time.

A lambda creates exactly that: a small unnamed callable object, written where it is used. [threshold](int value) { return value >= threshold; } has three parts. The brackets list the captures, local variables the lambda keeps with it. The parentheses are the parameters, as in any function. The braces are the body, and the return type is worked out from the return statement. A lambda that returns true or false for one element is called a predicate, and algorithms such as std::count_if and std::find_if call it once per element.

Predict and run

The lambda captures threshold, and then threshold changes. Which value does the count use?

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

int main() {
    std::vector<int> values{10, 25, 40};
    int threshold = 25;
    auto long_session = [threshold](int value) { return value >= threshold; };
    threshold = 50;
    std::cout << std::count_if(values.begin(), values.end(), long_session) << "\n";
    return 0;
}
Check your prediction
Text
2

[threshold] captures by value: the lambda object stores its own copy, 25, at the moment it is created. Changing the local afterward does not affect the copy, so 25 and 40 match. This is usually what a report wants: the rule is fixed when you build it.

Value capture and reference capture

Writing [&threshold] captures by reference instead. The lambda then refers to the local variable itself and sees every later change:

Copy versus reference C++
#include <algorithm>
#include <iostream>
#include <vector>

int main() {
    std::vector<int> values{10, 25, 40};
    int threshold = 25;
    auto by_copy = [threshold](int value) { return value >= threshold; };
    auto by_reference = [&threshold](int value) { return value >= threshold; };
    threshold = 40;
    std::cout << "copy: " << std::count_if(values.begin(), values.end(), by_copy) << "\n";
    std::cout << "reference: " << std::count_if(values.begin(), values.end(), by_reference) << "\n";
    return 0;
}
Text
copy: 2
reference: 1

Reference capture avoids a copy and can be right for large data the lambda only reads, but it is a borrow: the lambda must not be used after the variable it refers to is destroyed. That is easy to break when a function returns a lambda:

C++
auto make_filter(int limit) {
    return [&limit](int value) { return value >= limit; }; // limit dies when the function returns.
}

Every later call reads a parameter that no longer exists, which is undefined behavior; it may even give the right answer until the stack memory is reused. Capturing by value, [limit], makes the returned lambda own its copy and fixes it. Prefer explicit capture lists over the shortcuts [=] (copy everything used) and [&] (borrow everything used), so a reader can see what the lambda depends on.

Algorithms that take predicates

Most questions a report asks are a predicate plus an algorithm:

  • std::count_if returns how many elements match.
  • std::find_if returns an iterator to the first match, or end().
  • std::any_of, std::all_of, std::none_of return bool. On an empty range, all_of and none_of are true and any_of is false.

A predicate should only read its argument. Take it by value for small types and by const reference for records, and do not change anything outside the lambda, because the standard does not promise how many times or in which order an algorithm calls it.

Predicates over records C++
#include <algorithm>
#include <iostream>
#include <vector>

struct Task {
    int id;
    int minutes;
    bool done;
};

int main() {
    std::vector<Task> tasks{{1, 10, true}, {2, 25, false}, {3, 40, false}};
    int limit = 20;
    auto pending_long = [limit](const Task& task) { return !task.done && task.minutes >= limit; };
    std::cout << "pending long: " << std::count_if(tasks.begin(), tasks.end(), pending_long) << "\n";
    auto first = std::find_if(tasks.begin(), tasks.end(), pending_long);
    if (first != tasks.end()) { std::cout << "first is id " << first->id << "\n"; }
    std::cout << "all done: " << std::all_of(tasks.begin(), tasks.end(),
        [](const Task& task) { return task.done; }) << "\n";
    return 0;
}
Text
pending long: 2
first is id 2
all done: 0

The last lambda has empty brackets because it uses nothing from the surrounding function. std::count_if returns a signed count type (std::ptrdiff_t for a vector), which is why code that stores it in a std::size_t uses static_cast.

Practice

Exercise

Your turn

Write std::size_t count_at_least(const std::vector<int>& values, int threshold) with std::count_if, and std::optional<int> first_at_least(const std::vector<int>& values, int threshold) with std::find_if. Both use a lambda that captures threshold by value. For {10, 25, 40}, print:

Text
at least 25: 2, first 25
at least 40: 1, first 40
at least 41: 0, first none
empty: 0, first none
Predicate checked
Your workspace C++
#include <algorithm>
#include <iostream>
#include <optional>
#include <vector>

// Write count_at_least and first_at_least here.

int main() {
    std::vector<int> values{10, 25, 40};
    return 0;
}
Hint 1: the idea

The lambda answers one question for each element: is this value at least the threshold? Both functions ask the same question; they differ only in what the algorithm does with the answers.

Hint 2: a first step

Start with count_at_least, the shorter one: write the lambda first as a named variable, auto at_least = [threshold](int value) { ... };, and pass it to std::count_if. Print the first column of the expected output and check it before you start first_at_least. For that one, std::find_if returns an iterator, so decide what the result means when it equals values.end().

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

std::size_t count_at_least(const std::vector<int>& values, int threshold) {
    return static_cast<std::size_t>(std::count_if(values.begin(), values.end(),
        [threshold](int value) { return value >= threshold; }));
}

std::optional<int> first_at_least(const std::vector<int>& values, int threshold) {
    auto found = std::find_if(values.begin(), values.end(),
        [threshold](int value) { return value >= threshold; });
    if (found == values.end()) { return std::nullopt; }
    return *found;
}

void show(const char* label, const std::vector<int>& values, int threshold) {
    auto first = first_at_least(values, threshold);
    std::cout << label << ": " << count_at_least(values, threshold) << ", first "
              << (first ? std::to_string(*first) : "none") << "\n";
}

int main() {
    std::vector<int> values{10, 25, 40};
    show("at least 25", values, 25);
    show("at least 40", values, 40);
    show("at least 41", values, 41);
    show("empty", {}, 25);
    std::cout << "Predicate checked\n";
    return 0;
}
Text
at least 25: 2, first 25
at least 40: 1, first 40
at least 41: 0, first none
empty: 0, first none
Predicate checked

Thresholds 40 and 41 are the boundary pair: with > instead of >=, the second line would print 0 and none. first_at_least returns a copy of the value, not the iterator, so the result stays valid whatever happens to the vector later. The next lesson uses a lambda with two parameters, a comparator, to put a report in a fixed order.

Was this article helpful?

Your response is saved on this device.