// Syntax: [capture](params) -> return_type { body }
auto square = [](int x) { return x * x; };
cout << square(5); // 25
// With STL algorithms
vector<int> v = {3,1,4,1,5,9};
sort(v.begin(), v.end(), [](int a, int b) { return a > b; }); // descending
int evens = count_if(v.begin(), v.end(), [](int x){ return x%2==0; });
int threshold = 5;
auto isAbove = [threshold](int x) { return x > threshold; }; // capture by value
auto addTo = [&threshold](int x){ return x + threshold; }; // capture by ref
auto all = [=](int x){ return x > threshold; }; // all by value
auto allRef = [&](int x){ threshold++; return x; }; // all by ref
Write applyToAll(vector<int> v, function<int(int)> fn) that applies fn to every element and returns the result vector.
Click "Run" to execute your code.