Lambdas
In the Algorithms lesson, greater<int>() told sort to put larger numbers first. But what if you want to sort words by their length? There is no ready-made rule for that, so you write your own. The short way to do it is a lambda: a small function with no name, written right where you need it.
#include <iostream>
#include <vector>
#include <string>
#include <algorithm>
using namespace std;
int main() {
vector<string> names = {"Olivia", "Bob", "Emma"};
sort(names.begin(), names.end(),
[](string a, string b) {
return a.length() < b.length();
});
for (string name : names) {
cout << name << "\n";
}
return 0;
}
Output:
Bob
Emma
Olivia
The lambda is the third argument of sort. It has three parts:
| Part | Meaning |
|---|---|
[] | starts the lambda |
(string a, string b) | its parameters, like a normal function |
{ return ...; } | its body |
While sorting, sort calls the lambda many times, each time with two names. The lambda returns true when a should come before b. Here that means "the shorter name goes first", so Bob (3 letters) comes before Emma (4) and Olivia (6).
To sort numbers from largest to smallest, return a > b:
vector<int> waits = {40, 10, 25, 10};
sort(waits.begin(), waits.end(),
[](int a, int b) { return a > b; });
for (int w : waits) {
cout << w << " ";
}
cout << "\n";
Output:
40 25 10 10
count_if
count from the Algorithms lesson counts values equal to one value. count_if counts the values for which a lambda returns true. This lambda takes one value and checks if it is more than 20:
cout << count_if(waits.begin(), waits.end(),
[](int w) { return w > 20; })
<< "\n";
Output:
2
Only 40 and 25 are more than 20. Many other algorithms take a lambda in the same way. You will meet more of them in the next lesson.
Using a variable from outside
A lambda cannot use the variables around it unless you ask. This program tries to use limit inside the lambda:
#include <iostream>
#include <vector>
#include <algorithm>
using namespace std;
int main() {
vector<int> waits = {40, 10, 25, 10};
int limit = 5;
cout << count_if(waits.begin(), waits.end(),
[](int w) { return w > limit; });
return 0;
}
Output:
main.cpp: In lambda function:
main.cpp:10:32: error: ‘limit’ is not captured
The fix is to write the variable's name inside the square brackets: [limit]. This is called capturing the variable. The lambda gets its own copy of limit:
vector<int> waits = {40, 10, 25, 10};
int limit = 5;
cout << count_if(waits.begin(), waits.end(),
[limit](int w) { return w > limit; })
<< "\n";
Output:
4
All four waits are more than 5, so count_if returns 4.
Saving a lambda in a variable
You can also store a lambda in a variable and call it like a function. A lambda's type has no name that you can write, so use auto from the Data Types lesson and let the compiler work out the type:
auto square = [](int x) { return x * x; };
cout << square(4) << "\n";
cout << square(9) << "\n";
Output:
16
81
In the exercise, complete the lambda so sort puts the words in order from shortest to longest.