C++ - Lambdas & Functional Utilities

Overview

Estimated time: 50–70 minutes

Use lambdas to write concise functions inline. Understand captures, std::function, and how to compose with algorithms.

Learning Objectives

  • Write lambdas with value/reference captures and capture defaults.
  • Use lambdas with standard algorithms for clarity.
  • Know when to use std::function vs templates for callables.

Prerequisites

Lambda basics

#include <iostream>
int main(){
  auto add = [](int a,int b){ return a+b; };
  std::cout << add(2,3) << "\n";
}

Captures

#include <iostream>
int main(){
  int x=1, y=2;
  auto f = [x,&y]{ return x + y; }; // copy x, reference y
  y = 5;
  std::cout << f() << "\n"; // 1+5=6
}

std::function vs templates

#include <functional>
#include <iostream>
void call(std::function<int(int)> fn){ std::cout << fn(3) << "\n"; }

template <class F>
void call_fast(F fn){ std::cout << fn(3) << "\n"; }

int main(){ auto sq = [](int n){ return n*n; }; call(sq); call_fast(sq); }

Beginner Boosters

#include <vector>
#include <algorithm>
#include <iostream>
int main(){
  std::vector<int> v{1,2,3,4};
  std::for_each(v.begin(), v.end(), [](int& x){ x*=2; });
  for (int x: v) std::cout << x << ' '; // 2 4 6 8
}

Common Pitfalls

  • Capturing references to objects that go out of scope (dangling references).
  • Overusing std::function where a template parameter would be faster.

Checks for Understanding

  1. What does [=] vs [&] capture?
  2. When is std::function appropriate vs a template callable?
Show answers
  1. [=] captures by value by default; [&] captures by reference by default.
  2. Use std::function when type erasure and runtime polymorphism are needed; templates for speed and compile-time polymorphism.

Exercises

  1. Write a lambda that captures a counter by reference and increments it on each call.
  2. Use transform with a lambda to uppercase a vector<char>.