C++
Lambdas with STL
Learn to use lambdas with STL algorithms.
Lambdas with STL
STL algorithms often take a lambda. By passing a lambda as the third parameter to std::sort you get custom comparison. Example: std::sort(v.begin(), v.end(), [](int a, int b) { return a > b; }); sorts descending.
std::find_if and std::count_if also use lambdas. std::find_if returns the first element matching a condition, std::count_if returns the count of matching elements. Example: std::count_if(v.begin(), v.end(), [](int x) { return x % 2 == 0; }) counts even numbers. Lambdas make these algorithms very powerful; no separate function is needed.
find_if and count_if
std::find_if finds the first element matching a condition. The condition is a lambda returning bool: std::find_if(v.begin(), v.end(), [](int x) { return x > 10; }). If the returned iterator equals v.end() nothing was found.
std::count_if gives the count of elements matching a condition. For example std::count_if(v.begin(), v.end(), [](int x) { return x % 2 == 0; }) returns the number of even values. These two algorithms are the most common ways to pass lambdas to STL. Thanks to lambdas the condition is written at the call site; no separate function is needed.
Exercise Sort descending with a lambda
Sort v = {3, 1, 4, 1, 5} in descending order with std::sort. Pass the lambda [](int a, int b) { return a > b; } as the third parameter. Print the result in a for loop with spaces.
Show example solution
#include <iostream>
#include <vector>
#include <algorithm>
int main() {
std::vector<int> v = {3, 1, 4, 1, 5};
std::sort(v.begin(), v.end(), [](int a, int b) { return a > b; });
for (int x : v) {
std::cout << x << " ";
}
return 0;
}
Test yourself
-
Which STL algorithm sorts with a lambda comparator?
std::sort(v.begin(), v.end(), [](int a, int b) { ... });
- std::sort
- std::find
- std::count
- std::accumulate
Show answer
std::sort — std::sort sorts with a custom lambda.
-
Descending sort lambda
std::sort(v.begin(), v.end(), [](int a, int b) { return a ____ b; });
Show answer
std::sort(v.begin(), v.end(), [](int a, int b) { return a > b; });
-
Match each algorithm to its use
- std::sort + lambda
- Custom sort
- std::find_if + lambda
- Search by condition
- std::count_if + lambda
- Count by condition
- [](int x) { return x % 2 == 0; }
- Even number condition
Next lesson: std::function