c++ lambda学习举例
2022/8/22 1:55:34
本文主要是介绍c++ lambda学习举例,对大家解决编程问题具有一定的参考价值,需要的程序猿们随着小编来一起学习吧!
#include <iostream> #include<vector> #include<algorithm> #include<cmath> #include<ctime> using std::cout; using std::vector; using std::srand; using std::time; using std::generate; using std::endl; using std::count_if; using std::for_each; using std::rand; const long Size = 390000L; int main() { std::cout << "Hello World!\n"; vector<int> numbers(Size); srand(time(0)); generate(numbers.begin(), numbers.end(), rand); cout << "Sample Size=" << Size << endl; int m = 3; int count3 = count_if(numbers.begin(), numbers.end(), [m](int x) { return x % m == 0; }); cout << "mode by 3==0's count=" << count3 << endl; int count13 = count_if(numbers.begin(), numbers.end(), [](int x)->bool {return x % 13 == 0; }); cout << "mode by 13==0's count=" << count13 << endl; count3 = 0; count13 = 0; cout << "=====================\n"; for_each(numbers.begin(), numbers.end(), [&count3, &count13](int x) {count3 += x % 3 == 0; count13 += x % 13 == 0; }); cout << "mode by 3==0's count=" << count3 << endl; cout << "mode by 13==0's count=" << count13 << endl; int* p1 = new int(0); int* p2 = new int(0); cout << "=====================\n"; for_each(numbers.begin(), numbers.end(), [=](int x) {*p1 += x % 3 == 0; *p2 += x % 13 == 0; }); cout << "mode by 3==0's count=" << *p1 << endl; cout << "mode by 13==0's count=" << *p2 << endl; delete p1; delete p2; int* p3= new int[2]; p3[0] = 0; p3[1] = 0; cout << "=====================\n"; for_each(numbers.begin(), numbers.end(), [=](int x) {*p3+= x % 3 == 0; p3[1] += x % 13 == 0; }); cout << "mode by 3==0's count=" << *p3 << endl; cout << "mode by 13==0's count=" << p3[1] << endl; delete[]p3; }在lambda中 返回类型可以根据 函数体的返回值自动确定。 也可以[](int x)->bool这样明确指出来。 返回为void 可以不写。 [=],表示表达式内部可访问外部的所有动态变量,指针 new什么创建的变量。 [&count3],表示访问count3的引用,没有创建副本,这样可以给count3赋值。 int m=3; [m] (int x) { return x % m == 0; },这种不可以在表达式内部赋值,只在表达式里做只读变量。 lambda 省略了函数名用索引代替,入参有的话还是需要要写类型 比如 int x。 需要特定访问符号才能访问到表达式外部的变量。
这篇关于c++ lambda学习举例的文章就介绍到这儿,希望我们推荐的文章对大家有所帮助,也希望大家多多支持为之网!
- 2024-05-09flutter3.x_macos桌面os实战
- 2024-05-09Rust中的并发性:Sync 和 Send Traits
- 2024-05-08使用Ollama和OpenWebUI在CPU上玩转Meta Llama3-8B
- 2024-05-08完工标准(DoD)与验收条件(AC)究竟有什么不同?
- 2024-05-084万 star 的 NocoDB 在 sealos 上一键起,轻松把数据库编程智能表格
- 2024-05-08Mac 版Stable Diffusion WebUI的安装
- 2024-05-08解锁CodeGeeX智能问答中3项独有的隐藏技能
- 2024-05-08RAG算法优化+新增代码仓库支持,CodeGeeX的@repo功能效果提升
- 2024-05-08代码报错不用愁,CodeGeeX一键完成代码修复、错误解释的功能上线了!
- 2024-05-08今天开始程序员不用再发愁写commit message了,全部由CodeGeeX自动完成!