Menu
CoddyTech

Lambda 表达式与捕获

Coddy 面向 Go 开发者的 C++ 课程的第 24 课,共 48 课。

Go 闭包会捕获生命周期可以延长的变量。C++ 的引用捕获不会延长对象的生命周期。C++ 闭包会显式捕获值或引用。引用捕获的生命周期不能超过其引用对象的生命周期。

Go

package main
import (
 "fmt"
)
func counter() func() int { n:=0; return func() int { n++; return n } }
func main() {
 next:=counter(); fmt.Println(next(),next())
}

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 f=[n](int x){return x+n;};n=9;std::cout<<f(3)<<"\n";
}

分别跟踪每个程序。这些示例使用与任务中不同的操作或数据来演示这个概念,不假设源代码和目标代码的输出相同。

challenge icon

挑战

简单

第一行输入 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";
}
quiz icon自我测试

这节课包含一个小测验。开始学习即可作答,并记录你的进度。

面向 Go 开发者的 C++中的所有课

自己练习: C++ 在线编译器