C++ 的 Lambda捕获
等级 5544 次按键
展示 lambda 的捕获方式:[=] 复制变量,[&] 引用变量,捕获列表可以混用两者,带 mutable 的初始化捕获会创建在多次调用之间保留的状态。
C++ 代码
1int multiplier = 10;2string prefix = "Result: ";3 // [=] 在创建 lambda 时复制 multiplier(10)和 prefix4auto byValue = [=](int x) { return prefix + to_string(x * multiplier); };// [&] 引用原变量,因此可以修改 multiplier5auto byRef = [&](int x) { multiplier += x; return multiplier; };// 混合:multiplier 按引用捕获,prefix 按值捕获6auto mixed = [&multiplier, prefix](int x) { // 修改原来的 multiplier7 multiplier *= x;8 return prefix + to_string(multiplier);9};10 // 使用之前的副本:5 × 10,输出“Result: 50”11cout << byValue(5) << endl;// multiplier 变为 10 + 3 = 1312cout << "After byRef(3): " << byRef(3) << endl;// multiplier 变为 13 × 2 = 26:输出“Result: 26”13cout << mixed(2) << endl;14 // 初始化捕获在 lambda 内创建 total;mutable 允许修改它15auto initCapture = [total = 0](int x) mutable { return total += x; };// total 在调用之间保留:先 5 后 8(C++17 起保证从左到右求值)16cout << "Running total: " << initCapture(5) << ", " << initCapture(3) << endl;运行结果
Result: 50 After byRef(3): 13 Result: 26 Running total: 5, 8
可以用这段代码练习打字。成绩不会计入排行榜。
这段代码中的符号
这段 C++ 代码中需要输入的符号及其出现次数。
<× 24;× 16(× 12)× 12=× 11"× 8[× 4]× 4{× 4}× 4