Algorithms and lambdas
Course contents (20 lessons)
- Getting started
- Setting up a C++ compiler and writing your first program
- Variables, types and reading input
- Control flow, functions and indirection
- Control flow: if, switch and loops
- Functions: parameters, return values and overloading
- References and pointers
- Working with data
- Arrays and std::vector
- Working with std::string and string_view
- Classes and object-oriented design
- Structs and classes: your own types
- Constructors, destructors and RAII
- Operator overloading
- Inheritance and virtual functions
- Generic code and the STL
- Templates: writing generic code
- The STL: containers and iterators
- Algorithms and lambdas
- Ownership, moves and errors
- Smart pointers and ownership
- Move semantics and perfect forwarding basics
- Error handling: exceptions, optional and expected
- Modern C++ and a real project
- Modern C++: ranges, concepts and std::format
- Building projects with CMake
- Final project: a command-line expense tracker
Say what, not how
Many loops do one of a small number of jobs: find something, count something, transform every element, sum them up, sort them. The header <algorithm> has a named function for each. Using them makes the intent visible in one line, and they are well tested and usually well optimised. They need a way to describe what to do with each element, and that is where lambdas come in.
Lambdas
A lambda is a small unnamed function you write in the middle of an expression.
auto isEven = [](int n) { return n % 2 == 0; };
std::cout << std::boolalpha << isEven(4) << " " << isEven(7) << "\n"; // true false
The pieces: square brackets for the capture list, round brackets for parameters, then the body in braces. The return type is deduced. The lambda is an object, so you can store it in auto, pass it to functions and call it.
Captures
A lambda can use variables from the surrounding scope if you list them in the brackets.
int threshold{50};
auto aboveLimit = [threshold](int x) { return x > threshold; }; // copy
auto addToTotal = [&total](int x) { total += x; }; // reference
auto everything = [=](int x) { return x + threshold; }; // copy all used
auto byRef = [&](int x) { return x + threshold; }; // reference all used
Capture by copy [x] takes a snapshot when the lambda is created. Capture by reference [&x] sees changes but dies with the variable. If you return a lambda from a function, or store it for later, a reference capture of a local variable becomes a dangling reference. Capture by copy for anything that outlives the scope. I list captures explicitly rather than using [=] or [&], because it shows the reader what the lambda depends on.
By default a lambda cannot modify its by-copy captures. Add mutable after the parameter list if you really want that, but it is rarely a good sign.
The workhorse algorithms
Here is a realistic example with a list of products.
#include <algorithm>
#include <iostream>
#include <numeric>
#include <string>
#include <vector>
struct Product {
std::string name;
double price;
int stock;
};
int main() {
std::vector<Product> items{
{"keyboard", 49.0, 12},
{"mouse", 19.5, 0},
{"monitor", 189.0, 4},
{"cable", 4.0, 100},
};
// sort by price, cheapest first
std::sort(items.begin(), items.end(),
[](const Product& a, const Product& b) { return a.price < b.price; });
// find the first one that is out of stock
auto out = std::find_if(items.begin(), items.end(),
[](const Product& p) { return p.stock == 0; });
if (out != items.end()) std::cout << "out of stock: " << out->name << "\n";
// count items worth more than 40
auto pricey = std::count_if(items.begin(), items.end(),
[](const Product& p) { return p.price > 40.0; });
std::cout << "pricey: " << pricey << "\n";
// total value of stock
double value = std::accumulate(items.begin(), items.end(), 0.0,
[](double sum, const Product& p) { return sum + p.price * p.stock; });
std::cout << "stock value: " << value << "\n";
// build a list of names with transform
std::vector<std::string> names(items.size());
std::transform(items.begin(), items.end(), names.begin(),
[](const Product& p) { return p.name; });
for (const auto& n : names) std::cout << n << " ";
std::cout << "\n";
}
Walk through it. sort takes a comparison: return true if a should come before b. find_if returns an iterator to the first match, or end() if there is none. count_if returns how many match. accumulate from <numeric> folds the range into one value, starting from the third argument; note the 0.0, which makes the sum a double. If you wrote 0, the sum would be an int and the decimals would be lost. That is a classic bug. Finally, transform writes one output per input, and the destination must already have room, which is why names is created with the right size.
Other algorithms to know
std::any_of,all_of,none_of: yes or no questions about a range.std::min_element,max_element: return iterators.std::reverse,std::rotate,std::unique(works on sorted data).std::copy_ifwithstd::back_inserter: filter into a new vector.std::remove_if: moves unwanted items to the end and returns the new end; combine it witherase.
std::vector<int> nums{5, 12, 8, 21, 3, 16};
std::vector<int> big;
std::copy_if(nums.begin(), nums.end(), std::back_inserter(big),
[](int n) { return n > 10; }); // 12 21 16
// erase-remove idiom (pre C++20 style)
nums.erase(std::remove_if(nums.begin(), nums.end(),
[](int n) { return n < 10; }),
nums.end());
The erase-remove pairing confuses people because remove_if does not actually shrink the vector. It cannot, since it only sees iterators, not the container. It shifts the kept elements forward and hands back the new logical end. The erase call then cuts the tail off. C++20's std::erase_if wraps the two for you.
When a plain loop is better
Algorithms are not a religion. If a loop needs several different things done in one pass, early exits, or has complicated state, a range-based for loop is clearer. Choose the one a colleague can read fastest.
The common mistake
Passing a comparison to sort that is not a strict weak ordering. Writing a.price <= b.price instead of < looks harmless, but it can make std::sort read outside the array and crash. The comparison must return false for equal elements. Another one is calling transform into an empty vector and wondering why nothing appears. And the integer 0 instead of 0.0 in accumulate.
Try it yourself
- Given a vector of words, sort them by length, and alphabetically among equal lengths, using one lambda.
- Use
copy_ifandback_inserterto collect all products with stock below five into a new vector. - Write a function that returns a lambda adding a fixed amount,
makeAdder(int n), and check why capturingnby copy matters.
auto isEven = [](int n) { return n % 2 == 0; };
std::cout << std::boolalpha << isEven(4) << " " << isEven(7) << "\n"; // true false
This course is free to read. Create a free account to enrol, save your progress and pick up where you left off.
Sign up free I already have an account