C++
Summary - Lambda
Combine capture, STL and std::function to write a filter function.
Summary - Lambda
In this group you learned what lambdas are, the [](){} syntax, capture modes, use with STL and std::function. Now we combine these to write a filter function.
First we will count even numbers using a lambda with std::count_if. Then we will store that lambda in a std::function and reuse it. This shows how the combination of lambda + STL + std::function works in a real scenario.
Exercise Count even numbers with a lambda
For v = {1, 2, 3, 4, 5, 6}, use std::count_if with a lambda to count even numbers. The lambda is [](int x) { return x % 2 == 0; }. Print the result with std::cout.
Show example solution
#include <iostream>
#include <vector>
#include <algorithm>
int main() {
std::vector<int> v = {1, 2, 3, 4, 5, 6};
int n = std::count_if(v.begin(), v.end(), [](int x) { return x % 2 == 0; });
std::cout << n;
return 0;
}
Exercise Store the lambda in std::function
Add #include <functional>. Store the lambda with std::function<bool(int)> isEven = [](int x) { return x % 2 == 0; };. Then count even numbers with std::count_if(v.begin(), v.end(), isEven) and print the result.
Show example solution
#include <iostream>
#include <vector>
#include <algorithm>
#include <functional>
int main() {
std::vector<int> v = {1, 2, 3, 4, 5, 6};
std::function<bool(int)> isEven = [](int x) { return x % 2 == 0; };
int n = std::count_if(v.begin(), v.end(), isEven);
std::cout << n;
return 0;
}
Lambda recap
Lambda expressions are anonymous functions in C++. They use the syntax [capture](params) -> type { body }. The capture clause captures outer variables: [=] by value, [&] by reference.
They form a powerful pair with STL algorithms: std::sort, std::find_if, std::count_if and similar take lambdas for custom conditions. std::function stores a lambda in an object for reuse. In the next group you will learn smart pointers, which will make memory management safe.
Test yourself
-
What is used to store a lambda for later calling?
auto f = [](int x) { return x; };
- std::sort
- std::find
- std::function
- std::count
Show answer
std::function — std::function is the general type for storing lambdas.
-
Complete the count_if call
int n = std::____(v.begin(), v.end(), [](int x) { return x % 2 == 0; });
Show answer
int n = std::count_if(v.begin(), v.end(), [](int x) { return x % 2 == 0; });
Next lesson: std::unique_ptr