C++ Lambda简明教程

  • C++ Primer Plus 中文 第六版
  • Essential C++ 中文版
  • 深度探索 C++ 对象模型
  • C++ 程序设计语言(1-3)(4) 第四版 英文版
  • A Tour of C++ (Second Edition)
  • Professional C++ (4th Edition)

Lambda

Expressions 表达式

[capture](parameters) -> returnType{
 statements;
}

Capture 关键字

When a lambda definition is executed, for each variable that the lambda captures, a clone of that variable is made (with an identical name) inside the lambda. These cloned variables are initialized from the outer scope variables of the same name at this point.

The captured variables of a lambda are clones of the outer scope variables, not the actual variables

Capture by reference
Capture by value
Capture by both (mixed capture)
int health{ 33 };
int armor{ 100 };
std::vector enemies{};

[](){}; //default 

//capture health by value 
[health](){}

//can update health value with mutable
[health]() mutable{}

// Capture health and armor by value, and enemies by reference.
[health, armor, &enemies](){};
 
// Capture enemies by reference and everything else by value.
[=, &enemies](){};
 
// Capture armor by value and everything else by reference.
[&, armor](){};
 
// Illegal, we already said we want to capture everything by reference.
[&, &armor](){};
 
// Illegal, we already said we want to capture everything by value.
[=, armor](){};
 
// Illegal, armor appears twice.
[armor, &health, &armor](){};
 
// Illegal, the default capture has to be the first element in the capture group.
[armor, &](){};

Examples 例子

std::string label = "nut";
std::array arr{"apple", "banana", "walnut", "lemon"};

// std::find_if takes a pointer to a function
const auto found{std::find_if(arr.begin(), arr.end(), [&label](std::string str) {
     label = "apple";
     return (str.find(label) != std::string::npos);
 })};
auto print = [](auto value) {
        static int count{0};
        std::cout << "count: " << count++ << "value: " << value << std::endl;
    };

print("a");
print("b");
print(1);
print(2);

//we define a lambda and then call it with two different parameters 
//(a string literal parameter, and an integer parameter). This generates 
//two different versions of the lambda (one with a string literal parameter, 
//and one with an integer parameter).

//Most of the time, this is inconsequential. However, note that if the generic 
//lambda uses static duration variables, those variables are not shared between the 
//generated lambdas. 

links:
https://www.learncpp.com/cpp-tutorial/introduction-to-lambdas-anonymous-functions/ https://www.learncpp.com/cpp-tutorial/lambda-captures/

你可能感兴趣的:(C++ Lambda简明教程)