Sometimes an algorithm needs a rule rather than a particular value. To count only long appointments, you need to test each duration. std::count_if takes a range and a callable rule. It calls that rule on each element and counts the elements for which the result is true. Such a true-or-false rule is called a predicate.
A lambda is a small function you can write at the place where it is needed. Read [](int minutes) { return minutes > 30; } in pieces: [] is the capture list, empty here because no surrounding variables are needed; (int minutes) declares one parameter; the braces contain the function body. The compiler infers the boolean return type from the comparison.
The algorithm supplies each element as the argument. You do not call the lambda yourself inside the algorithm call. A parameter passed by value is a local copy, which is enough for reading integers. Returning true means “count this element”; it does not mean the algorithm should stop.
#include <algorithm>
#include <iostream>
#include <vector>
int main() {
std::vector<int> minutes{20, 45, 35};
auto longVisits = std::count_if(minutes.begin(), minutes.end(),
[](int duration) { return duration > 30; });
std::cout << longVisits << '\n';
}
The example prints 2: the algorithm calls the lambda for every duration and counts the true results. In the editor, that calling machinery is already supplied. Replace false inside the lambda with the comparison for one book's page count. Do not write a loop inside the lambda; count_if does the repetition. Include the book exactly at the requested threshold.
count parameter is at least 120. The supplied algorithm should print Long books: 3.Edit main.cpp, then press Run to inspect the Console. Press Submit to check your work. Keep the supplied probes in place.