Use Lambdas as Predicates with the Algorithm Library
Explore how to apply lambda expressions as predicate functions in the C++20 algorithm library. Understand the interchangeability of functions, functors, and lambdas and how to use them with algorithms such as count_if to write concise and powerful code for condition-based operations.
We'll cover the following...
Some functions in the algorithm library require the use of a predicate function. A predicate is a function (or functor or lambda) that tests a condition and returns a Boolean true/false response.
How to do it
For this recipe, we will experiment with the count_if() algorithm using different types of predicates:
First, let’s create a function for use as a predicate. A predicate takes a certain number of arguments and returns a bool. A predicate for
count_if()takes one argument:
bool is_div4(int i) {return i % 4 == 0;}
This predicate checks whether an int value is divisible by 4. ...