Skip to content

STL Algorithms & Lambdas

The STL algorithms library <algorithm> is a collection of powerful, reusable functions that operate on ranges of elements. They decouple what you want to do from how it is done.

Common Algorithms

Sorting and Searching

#include <algorithm>
#include <vector>

std::vector<int> v = {5, 1, 4, 2, 3};

// Sort in ascending order
std::sort(v.begin(), v.end()); // 1, 2, 3, 4, 5

// Binary search (requires sorted range)
bool found = std::binary_search(v.begin(), v.end(), 3);

Modifying Sequences

1
2
3
4
5
6
7
// Fill with a value
std::fill(v.begin(), v.end(), 0);

// Transform (Map)
std::transform(v.begin(), v.end(), v.begin(), [](int n) {
    return n * n; // Square each element
});

Non-Modifying Operations

1
2
3
4
5
6
7
8
// Count occurrences
int count = std::count(v.begin(), v.end(), 0);

// Find an element
auto it = std::find(v.begin(), v.end(), 42);
if (it != v.end()) {
    // Found
}

Lambda Expressions

Lambdas are anonymous functions defined in-place. They are essential for using STL algorithms effectively.

Syntax

[captures](parameters) -> return_type { body }

Captures

  • []: No captures.
  • [=]: Capture all local variables by value (copy).
  • [&]: Capture all local variables by reference.
  • [x, &y]: Capture x by value, y by reference.
1
2
3
4
int factor = 2;
auto multiply = [factor](int n) {
    return n * factor;
};

Mutable Lambdas

By default, value captures are read-only. Use mutable to modify them (this modifies the lambda's copy, not the original).

1
2
3
4
int count = 0;
auto counter = [count]() mutable {
    return ++count;
};

C++20 Ranges

Ranges simplify the usage of algorithms by allowing you to pass the container directly, rather than begin() and end(). They also support piping.

#include <ranges>
#include <algorithm>
#include <vector>

std::vector<int> numbers = {1, 2, 3, 4, 5, 6};

// Filter even numbers and square them
auto results = numbers 
             | std::views::filter([](int n){ return n % 2 == 0; })
             | std::views::transform([](int n){ return n * n; });

for (int n : results) {
    std::cout << n << " "; // 4 16 36
}

Best Practices

  1. Prefer Algorithms over Loops: Algorithms are named after what they do (find, sort, count), making code more readable and less error-prone.
  2. Use Ranges (C++20): They are safer and more composable.
  3. Be Careful with Captures: Capturing pointers or references in lambdas that outlive the scope leads to dangling references.