
Learning website for technical articles:https://www.chengxuchu.com
Hello everyone, I am Chef, a programmer who loves cooking and has obtained a chef qualification certificate.
When writing C++ code, especially when dealing with callbacks, algorithms, or asynchronous operations, you may often encounter situations where you need to write a large number of function objects or define additional functions. The Lambda expressions introduced in C++11 were designed to solve these cumbersome and bloated coding issues.
From daily development to interviews, Lambda has almost become an unavoidable topic. Understanding the core problems it solves not only allows you to write more concise and efficient code but also helps you stand out in interviews.
1. Why Do We Need Lambda?
Before C++11, there were mainly the following methods to implement anonymous functions or short callbacks:
- Function Pointers: Can only point to regular functions and cannot capture context information.
- Function Objects (functors): Require additional definitions of structures or classes, leading to verbose and scattered code.
- **
<span>std::bind</span>**: Syntax is cumbersome and can affect code readability.
For example, to sort an array according to a custom rule:
#include <algorithm>
#include <vector>
#include <iostream>
bool compare(int a, int b) {
return a > b; // Descending order
}
int main() {
std::vector<int> v{3, 1, 4, 2};
std::sort(v.begin(), v.end(), compare);
for (int n : v) std::cout << n << ' ';
}
In this code, you must first define a separate function <span>compare</span> to pass it to <span>std::sort</span>. If it is only used once, it seems quite troublesome. In more complex scenarios, such as when the sorting rule needs to reference local variables, function pointers cannot achieve this at all.
2. What Has Changed with the Introduction of Lambda?
Lambda expressions allow us to write anonymous functions directly at the call site and can capture surrounding variables, greatly enhancing flexibility and conciseness.
Rewriting the previous example:
#include <algorithm>
#include <vector>
#include <iostream>
int main() {
std::vector<int> v{3, 1, 4, 2};
std::sort(v.begin(), v.end(), [](int a, int b) { return a > b; });
for (int n : v) std::cout << n << ' ';
}
Now, the sorting rule and the calling code are aggregated together, making the logic clearer.
3. Core Problems Solved by Lambda
- Simplifying Code Structure: In the past, to pass a “function”, one had to define a named function or structure. Lambda makes functions “first-class citizens” that can be written directly where needed in the code.
- Support for Capturing External Variables: Function pointers can only point to static functions and cannot access local variables. Lambda allows capturing by value or by reference, making it convenient to pass context.
- Improving Readability and Maintainability: Code is centralized, intentions are clear, and the burden of finding callback implementations is reduced.
- Support for Inline Definitions: For function logic that is only used once, there is no need for additional declarations, reducing namespace pollution.
4. Syntax Analysis of Lambda
The basic form of a Lambda is:
[capture](parameters) -> return_type {
function_body
}
- capture: Capture list, specifying which external variables to access (by value, by reference, etc.).
- parameters: Parameter list, similar to a regular function.
- return_type: Return type, which the compiler can usually infer automatically and is not required to be written.
- function_body: Function body.
Example:
int x = 10, y = 20;
auto f = [x, &y](int a) -> int {
return a + x + y;
};
y = 30;
std::cout << f(5) << std::endl; // Outputs 5 + 10 + 30 = 45
Here, <span>x</span> is captured by value, copying the value <span>10</span>, while <span>y</span> is captured by reference, and the modified value <span>30</span> is used in the function body.
5. Examples of Practical Applications
1. Standard Algorithms with Lambda
std::vector<int> nums{1, 2, 3, 4, 5};
int threshold = 3;
auto count = std::count_if(nums.begin(), nums.end(), [threshold](int n) {
return n > threshold;
});
std::cout << "Count greater than " << threshold << ": " << count << std::endl;
2. Event Callbacks
void registerCallback(std::function<void(int)> cb);
int main() {
int factor = 2;
registerCallback([factor](int value) {
std::cout << "Calculation result: " << value * factor << std::endl;
});
}
3. Passing Function Objects in Multithreading
#include <thread>
int main() {
int base = 100;
std::thread t([base]() {
for (int i = 0; i < 5; ++i) {
std::cout << base + i << std::endl;
}
});
t.join();
}
6. Common Interview Points Summary
- Lambda capture methods and differences (by value, by reference, implicit capture)
- The relationship between Lambda and function objects (underlying implementation)
- Callable object type
<span>std::function</span>and its combination with Lambda - Type inference and declaration methods of Lambda expressions
- The mutable keyword allows modification of captured by-value variables
7. Final Thoughts
The introduction of C++11 Lambda has made the use of functions more flexible and convenient, becoming an indispensable part of modern C++ programming. It not only solves the cumbersome traditional callback writing but also enhances the expressiveness of the code. Mastering it not only makes the code more concise but also makes the logic more compact and clear.
In interviews, explaining the role and principles of Lambda with specific examples will make you appear more professional and in-depth. It is recommended to use and practice it more in projects, familiarize yourself with its capture mechanisms and various details, and truly master it.
Recommended Reading:
C++ Direct Access to Major Companies
C++ Ridiculous Interview Questions: Is the vector object on the heap or stack?
In-depth Understanding of C++ Performance Optimization: From Memory Management to Compiler Optimization Practice

Hello, I am Chef! Graduated with a master’s degree in 211, I passed over 30 interviews during the autumn recruitment period and ultimately received more than 10 offers from companies such as Baidu, Tencent, Huawei, Shopee, Bilibili, SenseTime, JD, a military research institute, and one of the Big Four banks, mostly at the SP or SSP level.
My Tags:
- Former Full-Stack Developer at Tencent, currently an entrepreneur: Proficient in C++ development, self-rated 80 points.
- Open Source Project Author: One of my open-source repositories has surpassed 10,000+ stars and has topped the global trending list for a week.
- Campus Recruitment Offer Collector: During the autumn recruitment period, I received over 10 offers, almost all at the SP or SSP level.
- Deeply Understand the Confusion and Pain Points of Autumn Recruitment: Therefore, I established the “Xijia Training Camp”, which has been operating for 9 months, helping over 150 students significantly improve their C++ skills and successfully obtain ideal offers.
I particularly understand the confusion and difficulties everyone faces during autumn recruitment, so I hope to provide a clear direction and some practical methods through my experience.If you also want to stand out in the autumn recruitment, feel free to contact me (vx: chuzi345) to learn about the training camp we are running and join me in preparing for this autumn recruitment challenge!