Lambdas in C++
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]
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;
}
};