C++ Lambda Expressions — Complete Beginner Guide
Learning Objectives
- Read and write lambda syntax step by step
- Capture local values by value or reference
- Choose safe default capture modes
- Pass lambdas into algorithms and callbacks
A Function Without a Separate Name
A lambda is an inline function object you define right where it is needed. It keeps short logic close to its use site, which is ideal for sorting rules, filters, and event handlers.
#include <iostream>
int main() {
auto greet = []() {
std::cout << "hi from lambda" << std::endl;
};
greet();
return 0;
}
Anatomy of A Lambda
| Part | Example | Meaning |
|---|---|---|
| capture list | square brackets | What outer names are visible |
| parameters | parentheses | Inputs like a normal function |
| trailing return | minus greater than type | Optional result type |
| body | braces | Steps that run |
When the body is a single return expression, the compiler often deduces the result type for you.
auto add = [](int a, int b) {
return a + b;
};
For clarity on multi step bodies, write the return type explicitly after the parameter list.
Capture By Value
Capturing by value copies the outer variable into the lambda. Later changes outside do not affect the copy.
int factor = 3;
auto scale = [factor](int n) {
return n * factor;
};
| Mode | Syntax | Effect |
|---|---|---|
| By value | name in brackets | Snapshot copy |
| By reference | ampersand name | Live connection |
| This | this pointer form | Member access for classes |
Capture By Reference
Reference capture shares the outer variable. Mutations inside the lambda can be seen outside.
int total = 0;
auto accumulate = [&total](int n) {
total += n;
};
Danger alert: never let a reference captured lambda outlive the variable it points at. Dangling references produce undefined behavior.
Default Captures
Default modes grab unspecified names automatically.
int a = 5;
int b = 7;
auto sumA = [=]() { return a; }; // copy all used by value
auto addB = [&]() { return a + b; }; // reference all used
| Default | Meaning |
|---|---|
| empty brackets | Capture nothing |
| equals sign in brackets | Copy all omissions by value |
| ampersand in brackets | Reference all omissions |
| mixed lists | Explicit overrides of the default |
Prefer explicit captures in shared codebases. They document intent and reduce surprise writes.
Init Capture and Moving
Modern C plus plus allows capturing by moving a local into the lambda storage. This is helpful for unique ownership objects that cannot be copied.
auto owner = std::make_unique<int>(1);
auto useIt = [ptr = std::move(owner)]() {
if (ptr) return *ptr;
return 0;
};
You still see raw pointers and references in many examples; unique style capture closes the ownership story cleanly.
Lambdas With Standard Algorithms
This is the most common day to day use.
#include <algorithm>
#include <vector>
#include <iostream>
int main() {
std::vector<int> nums = {1, 2, 3, 4, 5, 6};
int evens = static_cast<int>(
std::count_if(nums.begin(), nums.end(),
[](int n) { return n % 2 == 0; }));
std::sort(nums.begin(), nums.end(),
[](int a, int b) { return a > b; });
std::cout << evens << std::endl;
return 0;
}
In source code the greater than symbol is used for descending order. Each lambda is a tiny policy injected into a generic algorithm.
Mutable Lambdas
By default, value captures are const inside the lambda body. The mutable keyword allows modifying copies without affecting outer variables.
int seed = 10;
auto copy = [seed]() mutable {
seed += 1; // changes only the captured copy
return seed;
};
Use mutable sparingly and only when local copy state is intentional.
Storing Lambdas
auto hides the long type name generated for each lambda. When you must store different lambdas together, a std::function wrapper can help at the cost of a little overhead.
#include <functional>
std::function<int(int, int)> op = [](int a, int b) {
return a + b;
};
Common Mistakes
| Mistake | Result |
|---|---|
| Reference capturing a temporary | Dangling reference risk |
| Default reference capture in large code | Hidden dependencies |
| Assuming value capture updates outer | Copies do not sync back |
| Heavy logic in one giant lambda | Extract a named function |
| Forgetting const on shared state | Unexpected mutation confusion |
A Practical Example
#include <algorithm>
#include <iostream>
#include <string>
#include <vector>
int main() {
std::vector<std::string> names = {"ann", "bea", "cy", "dan"};
int minLen = 3;
auto shortNames = [minLen](const std::string& s) {
return s.length() static_cast_less minLen;
};
names.erase(
std::remove_if(names.begin(), names.end(),
[minLen](const std::string& s) {
return s.length() < minLen;
}),
names.end());
for (const auto& n : names) {
std::cout << n << std::endl;
}
return 0;
}
The helper predicate in remove_if keeps the erase pattern clean. Compare lengths with the normal less than operator inside the lambda body.
Key Takeaways
💡
- Lambdas are inline function objects with a capture list
- Value captures snapshot; reference captures share live state
- Prefer explicit captures over broad defaults in shared code
- Main real world use is plugging logic into STL algorithms
- Never return a lambda that references expired locals
Practice Questions
- Write a lambda that returns true for numbers greater than ten.
- What is the difference between empty brackets and equals sign brackets?
- When would you mark a lambda mutable?
Extended Learning: Beyond the Basics
Key Concepts Summary
This lesson covers fundamental concepts that serve as building blocks for more advanced topics. Master these basics before moving to intermediate and advanced material.
Prerequisite Knowledge
Before studying this topic in depth, ensure you understand:
- Basic definitions and terminology
- Core formulas and their derivations
- Common applications in real-world scenarios
- Typical pitfalls and misconceptions
Step-by-Step Walkthrough
Let us work through a complete example to solidify understanding:
Step 1: Identify the problem type. Determine which category this problem falls into and which approach is most appropriate.
Step 2: Apply the relevant formula. Substitute known values into the appropriate equation, paying attention to units and constraints.
Step 3: Simplify and solve. Work through the algebra step by step, checking each intermediate result.
Step 4: Verify the answer. Check that the solution satisfies the original conditions and makes logical sense.
Common Mistakes to Avoid
- Misidentifying the problem type — Always start by categorizing the problem
- Incorrect formula application — Verify the formula applies to your specific case
- Unit errors — Always check units are consistent throughout
- Sign errors — Pay careful attention to positive and negative values
- Rounding too early — Keep full precision until the final answer
- Forgetting constraints — Check that solutions satisfy all given conditions
Real-World Applications
Understanding this concept is essential for:
- Advanced problem solving in examinations
- Building intuition for more complex topics
- Developing analytical thinking skills
- Applying mathematical reasoning to practical situations
Practice Exercises
- Basic: Solve 5 problems of increasing difficulty using the core concept.
- Intermediate: Apply the concept to word problems with multiple steps.
- Advanced: Combine this concept with 2-3 other topics in a comprehensive problem.
- Challenge: Create your own problem that requires this concept plus additional knowledge.
Interview and Exam Tips
- Common question patterns: Identify which exam or interview formats test this topic
- Time management: Practice completing problems within time constraints
- Common traps: Know the typical mistakes examiners set as distractors
- Verification strategy: Develop a quick method to check your answer
Related Topics
- Previous Topic — Build on the foundation laid here
- Next Topic — See how this concept extends to more advanced material
- Practice Problems — Additional exercises with solutions
- Video Explanation — Visual walkthrough of key concepts
Quick Reference Card
| Concept | Formula/Rule | Key Insight | Common Use |
|---|---|---|---|
| Core Definition | See main text | Understand the intuition | Foundation for all applications |
| Key Formula | See main text | Memorize the derivation | Direct problem solving |
| Special Case | See main text | Recognize when it applies | Simplifies complex problems |
| Edge Case | See main text | Know the limitations | Avoids errors |
Further Reading
For students who want to go deeper:
- Standard textbooks on the subject
- Research papers applying this concept
- Online courses with video explanations
- Practice problem collections with detailed solutions