Show contents
Chapter 4 of 7 · 20 min
Ranges and lambdas
By the end of this chapter, you'll be able to
- Write lambdas and choose how they capture variables
- Chain views with filter, transform and take
- Use std::ranges algorithms with projections
- Avoid dangling references in lambdas and views
Lambdas and their captures
A lambda is an anonymous function written on the spot. Between square brackets, its capture list says which local variables it can use, and how:
#include <algorithm>
#include <iostream>
#include <vector>
int main() {
std::vector<double> amounts{42.0, 15.5, 99.9, 7.0, 63.0};
double threshold = 20;
int above = 0;
auto exceeds = [threshold](double m) { return m > threshold; }; // capture by copy
auto count = [&above, &exceeds](double m) { // capture by reference
if (exceeds(m)) ++above;
};
std::for_each(amounts.begin(), amounts.end(), count);
std::cout << above << " amounts above " << threshold << '\n';
auto n = std::count_if(amounts.begin(), amounts.end(), [](double m) { return m < 10; });
std::cout << n << " small amount\n";
}
3 amounts above 20
1 small amount
[threshold]copiesthreshold's value when the lambda is created;[&above]keeps a reference: the lambda changes the real variable;[]captures nothing;[=]and[&]capture everything used, by copy or by reference. Prefer listing the captures: you can see at a glance what the lambda depends on.
Ranges: processing as a pipeline
A view is a way of looking at a collection without copying it: std::views::filter only shows some elements, std::views::transform shows each element transformed. You chain them with |, and the computation only happens during iteration:
#include <algorithm>
#include <iostream>
#include <ranges>
#include <string>
#include <vector>
struct Order {
std::string customer;
double amount;
bool paid;
};
int main() {
std::vector<Order> orders{
{"Ama", 42.0, true}, {"Bruno", 15.5, false}, {"Chen", 99.9, true}, {"Dina", 7.0, true}, {"Eko", 63.0, false}};
auto big_paid = orders
| std::views::filter([](const Order& o) { return o.paid && o.amount > 20; })
| std::views::transform([](const Order& o) { return o.customer; });
const char* separator = "";
for (const auto& name : big_paid) {
std::cout << separator << name;
separator = ", ";
}
std::cout << '\n';
double total = 0;
for (double m : orders | std::views::transform(&Order::amount)) total += m;
std::cout << "total: " << total << '\n';
std::ranges::sort(orders, std::ranges::greater{}, &Order::amount);
separator = "";
for (const auto& o : orders | std::views::take(2)) {
std::cout << separator << o.customer;
separator = ", ";
}
std::cout << '\n';
}
Ama, Chen
total: 227.4
Chen, Eko
std::views::transform(&Order::amount): a pointer to a member works directly as a function, "take theamountfield".std::ranges::sort(orders, std::ranges::greater{}, &Order::amount)sorts by decreasing amount. The last argument is a projection: the value to compare for each element.std::views::take(2)only shows the first two elements.- Views are lazy:
big_paidcontains nothing, it's a recipe applied during thefor.
Iteration ends: no intermediate vector was created.
Text description of the animation
- The for asks for a first element: the view fetches Ama.
- Ama passes the filter.
- transform gives her name, displayed straight away.
- Bruno is filtered out: transform is never called for him.
- Iteration ends: no intermediate vector was created.
Your turn
Worked exercise
Worked exercise: the podium
From a vector of runners {name, time in seconds, retired}, display the podium: the three best times among runners who didn't retire, in the format 1. Kiplagat (7612 s). Use std::ranges::sort with a projection, then views to filter and limit to three.
Hint 1
std::ranges::sort(runners, {}, &Runner::time). The empty braces {} choose the default comparison, std::ranges::less.Hint 2
std::views::filter(...) and std::views::take(3), and number them in the loop with a counter.Show the solution and common mistakes
#include <algorithm>
#include <iostream>
#include <ranges>
#include <string>
#include <vector>
struct Runner {
std::string name;
int time;
bool retired;
};
int main() {
std::vector<Runner> runners{
{"Lindqvist", 7801, false}, {"Kiplagat", 7612, false}, {"Moreira", 7590, true},
{"Haddad", 7705, false}, {"Okafor", 7650, false}};
std::ranges::sort(runners, {}, &Runner::time);
int rank = 1;
for (const auto& r : runners | std::views::filter([](const Runner& r) { return !r.retired; }) | std::views::take(3)) {
std::cout << rank++ << ". " << r.name << " (" << r.time << " s)\n";
}
}
1. Kiplagat (7612 s)
2. Okafor (7650 s)
3. Haddad (7705 s)
Moreira has the best time, but retired: the filter leaves him out, and take(3) takes the next three.
Common mistakes:
- Putting
take(3)before the filter: you keep the three best times, then remove Moreira, and only two runners are left on the podium. - Sorting a filtered view:
std::ranges::sortneeds direct access to the elements, whichfilterdoesn't provide. Sort the container first, filter afterwards.
Summary
- 1A lambda captures by copy [x] or by reference [&x]; list its captures explicitly.
- 2The views filter, transform and take are chained with | without copying data.
- 3Views are lazy: the computation happens during iteration.
- 4std::ranges algorithms accept a projection, such as &Order::amount.
- 5A lambda that outlives its scope must capture by copy.
Your progress is saved on this device. Create a free account to keep your progress on all your devices.