Tutorials / C++: From Basics to Modern C++ / Algorithms and lambdas

Algorithms and lambdas

16 min read cpp
Course contents (20 lessons)
  1. Getting started
  2. Setting up a C++ compiler and writing your first program
  3. Variables, types and reading input
  4. Control flow, functions and indirection
  5. Control flow: if, switch and loops
  6. Functions: parameters, return values and overloading
  7. References and pointers
  8. Working with data
  9. Arrays and std::vector
  10. Working with std::string and string_view
  11. Classes and object-oriented design
  12. Structs and classes: your own types
  13. Constructors, destructors and RAII
  14. Operator overloading
  15. Inheritance and virtual functions
  16. Generic code and the STL
  17. Templates: writing generic code
  18. The STL: containers and iterators
  19. Algorithms and lambdas
  20. Ownership, moves and errors
  21. Smart pointers and ownership
  22. Move semantics and perfect forwarding basics
  23. Error handling: exceptions, optional and expected
  24. Modern C++ and a real project
  25. Modern C++: ranges, concepts and std::format
  26. Building projects with CMake
  27. 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_if with std::back_inserter: filter into a new vector.
  • std::remove_if: moves unwanted items to the end and returns the new end; combine it with erase.
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

  1. Given a vector of words, sort them by length, and alphabetically among equal lengths, using one lambda.
  2. Use copy_if and back_inserter to collect all products with stock below five into a new vector.
  3. Write a function that returns a lambda adding a fixed amount, makeAdder(int n), and check why capturing n by copy matters.
cpp
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