#include <iostream>
#include <array>
#include <vector>
#include <algorithm>
using namespace Std;
int main ()
{
The simplest lambda expression
[](){};
A lambda expression is a function that can be assigned to a function pointer, or it can be appended with parentheses.
//
[] inside you can add some restrictions that restrict the use of external variables in lambda block statements. A total of four cases:
1. Whitespace indicates that external variables cannot be read and written.
2.= represents the ability to read access to external variables.
3.& represents the ability to read and write access to external variables.
4. Can fill in the & variable name or the variable name without &, plus the & variable can read and write, without & the variable can only read access.
//
() is the parameter of the function.
//
Inside {} is an expression of the function.
Example one: Assigning a lambda expression to a function pointer
void (*p) (int);
p = [] (int num) {cout << num << endl;};
P (1);
Example two: Using a lambda expression as a function
[] (int num) {cout << num << endl;};
[] (int num) {cout << num << Endl;} (1);
Example three: access to external variables
int temp1 = ten, temp2 = 20;
Auto Tempa = [=] () {cout << temp1 << endl << temp2 << Endl;};//can only read access to Temp1 and Temp2 at this time.
Tempa ();
Auto TEMPB = [&] () {temp1 = Temp2; cout << temp1 << endl << temp2 << Endl;};//can now Temp1 and Temp2 Read and write access, note: The variable read and write at this time is the original variable.
TEMPB ();
Auto TEMPC = [&temp1, Temp2] () {Temp1 = $; cout << temp1 << endl << temp2 << Endl;};//at this point you can Temp1 for read-write access, but only for TEMP2.
TEMPC ();
Auto TEMPD = [=] () mutable{temp1 = Temp2 = ten cout << temp1 << endl << temp2 << Endl;};//at this time You can read and write access to Temp1 and Temp2, but Temp1 and temp2 are copies of the original variables.
/*
Lambda expressions allow functions to be defined again within a function (anonymous functions), and lambda expressions are useful for traversing data structures.
*/
Example four: Accessing an array with a lambda expression
int arr1[5] = {1, 2, 3, 4, 5};
For_each (arr1, arr1 + 5, [] (int num) {cout << num << endl;});
Array<int, 5> arr2 = {1, 2, 3, 4, 5};
For_each (Arr2.begin (), Arr2.end (), [] (int num) {cout << num << endl;});
Cin.get ();
return 0;
}
C + + lambda expression review