C++ Lambda Expressions
A lambda expression is a small unnamed function written where it is used. A lambda can be stored in a variable and called like a function.
A lambda stored and called
The greet lambda has no parameters. It is stored in a variable and called twice.
#include <iostream>
int main() {
auto greet = [] {
std::cout << "Hello from a lambda\n";
};
greet();
greet();
return 0;
}Parameters and a return value
The add lambda takes two ints and returns their sum. The returned value prints like any function result.
#include <iostream>
int main() {
auto add = [](int a, int b) {
return a + b;
};
std::cout << "Sum: " << add(3, 4) << "\n";
std::cout << "Sum: " << add(10, 25) << "\n";
return 0;
}A lambda inside sort
The sort algorithm orders words by length here. The comparison comes from a lambda passed as an argument.
#include <algorithm>
#include <iostream>
#include <string>
#include <vector>
int main() {
std::vector<std::string> words = {"strawberry", "fig", "banana", "pear"};
std::sort(words.begin(), words.end(), [](const std::string& a, const std::string& b) {
return a.size() < b.size();
});
for (const std::string& word : words) {
std::cout << word << "\n";
}
return 0;
}Two lambdas chosen by an if
Two lambdas wait in two variables. An if statement picks which one runs.
#include <iostream>
int main() {
auto greet = [] {
std::cout << "Welcome in\n";
};
auto farewell = [] {
std::cout << "See you soon\n";
};
bool arriving = true;
if (arriving) {
greet();
} else {
farewell();
}
arriving = false;
if (arriving) {
greet();
} else {
farewell();
}
return 0;
}Example
#include <algorithm>
#include <iostream>
#include <vector>
int main() {
std::vector<int> scores = {42, 87, 65, 91, 58};
int passed = std::count_if(scores.begin(), scores.end(), [](int score) {
return score >= 60;
});
std::cout << "Passed: " << passed << "\n";
return 0;
}Key points
- A lambda starts with square brackets called the capture list.
- Every lambda in this lesson has an empty capture list.
- Parameters go in round brackets after the capture list.
- The lambda body sits in braces like a function body.
- A stored lambda is called through its variable name.
- A lambda can be passed straight into an algorithm as an argument.
In this example, a lambda tests each score inside count_if. Three scores reach 60 or more. The count prints as 3.
Note
The std::function type can hold a lambda in a named variable of a fixed type.
Try it Yourself
Edit the code, then press Run.
Running is simulated
Exercise
What does an empty capture list at the start of a lambda mean?