Lambdas in C++

Jimmy (xiaoke) Shen
1 min readAug 15, 2020

--

Learning through examples

A lambda expression can have more power than an ordinary function by having access to variables from the enclosing scope. We can capture external variables from enclosing scope by three ways :
Capture by reference
Capture by value
Capture by both (mixed capture)

Syntax used for capturing variables :
[&] : capture all external variable by reference
[=] : capture all external variable by value
[a, &b] : capture a by value and b by reference From [1]

791. Custom Sort String

class Solution {
public:
string customSortString(string S, string T) {
vector<int> m(28, 27);
for (int i = 0; i < S.length(); ++i)
{
m[S[i]-'a'] = i;
}
sort(T.begin(), T.end(),
[&] (char a, char b)
{
return m[a-'a'] < m[b - 'a'];
});
return T;
}
};

Reference

[1] https://www.geeksforgeeks.org/lambda-expression-in-c/#:~:text=C%2B%2B%2011%20introduced%20lambda%20expression,%2Dtype%20%7B%20definition%20of%20method%20%7D

--

--

No responses yet