Use lambdas as predicates with the algorithm library
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 forcount_if()
takes one argument:bool is_div4(int i) { return i % 4 == 0; }
This predicate checks whether an int
value is divisible by 4.
- In
main()
, we'll define a vector ofint
values, and use it to test our predicate function withcount_if()
:int main() { const vector<int> v{ 1, 7, 4, 9, 4, 8, 12, 10, 20 }; int count = count_if(v.begin(), v.end(), is_div4); ...