Lambda 表达式与捕获
Coddy 面向 Ruby 开发者的 C++ 课程的第 24 课,共 48 课。
Ruby 块或 lambda 捕获的是变量本身,而不是变量的值:当 factor 被重新赋值时,lambda 会看到新值。要固定一个值,Ruby 代码会在方法内部创建 lambda,而方法的参数是一个新的变量。C++ 值捕获会存储显式副本。C++ 闭包会显式捕获值或引用:创建 lambda 时,[n] 会复制 n,而 [&n] 会引用该变量,类似 Ruby 闭包。引用捕获的生命周期不得超过其所引用对象的生命周期。
Ruby
def multiplier(n)
->(x) { x * n }
end
factor = 2
live = ->(x) { x * factor }
snapshot = multiplier(factor)
factor = 3
puts "#{live.call(4)} #{snapshot.call(4)}"
C++
#include <iostream>
#include <string>
#include <vector>
#include <array>
#include <map>
#include <set>
#include <algorithm>
#include <memory>
#include <sstream>
#include <stdexcept>
#include <utility>
int main(){
int n=2;auto byValue=[n](int x){return x+n;};auto byRef=[&n](int x){return x+n;};n=9;std::cout<<byValue(3)<<" "<<byRef(3)<<"\n";
}
分别跟踪每个程序。这些示例通过与任务不同的操作或数据来展示这个概念,不假设源代码和目标代码的输出一致。
挑战
简单输入:第一行是 threshold,第二行是整数。返回严格大于 threshold 的值的数量。
在 exercise.hpp 和 exercise.cpp 中实现声明的 API。这两个文件都可以编辑;请保留公开签名。锁定的 main.cpp 会读取标准输入并直接调用 API。对于明确说明的情况,它还会独立检查公开 API 的行为。在 API 中返回值,不要打印。整数输入和结果都在有符号 int 的范围内;除非另有说明,文本均为 ASCII。
亲手试试
#include "exercise.hpp"
#include <iostream>
int main(){
std::vector<std::string> rows; std::string line; while(std::getline(std::cin,line)) rows.push_back(line);
int t=std::stoi(rows[0]);std::istringstream in(rows.size()>1?rows[1]:"");std::vector<int>v;int n;while(in>>n)v.push_back(n);std::cout<<above(v,t)<<"\n";
}
这节课包含一个小测验。开始学习即可作答,并记录你的进度。
面向 Ruby 开发者的 C++中的所有课
自己练习: C++ 在线编译器