C++中的Lambda
参考:C++ Primer Plus 中文版 第六版
例子代码:

#include <iostream> #include <vector> #include <string> //std::to_string #include <algorithm> //包括了#include <cstdlib> #include <ctime> using namespace std; bool f3(int x){return x%3 == 0;} bool f13(int x){return x%13 == 0;} int main() { vector<int> arr1(100); std::srand(std::time(0)); std::generate(arr1.begin(), arr1.end(), std::rand); //using function pointer int counter3 = std::count_if(arr1.begin(), arr1.end(), f3); int counter13 = std::count_if(arr1.begin(), arr1.end(), f13); cout << counter3 << " " << counter13 << endl; //使用函数对象 using functor class f_mod { int div; public: f_mod(int div=1):div(div){} bool operator()(int x) {return x%div == 0;} }; counter3 = counter13 = 0; counter3 = std::count_if(arr1.begin(), arr1.end(), f_mod(3)); counter13 = std::count_if(arr1.begin(), arr1.end(), f_mod(13)); cout << counter3 << " " << counter13 << endl; //使用 Lambda 表达式 using Lambda counter3 = counter13 = 0; counter3 = std::count_if(arr1.begin(), arr1.end(), [](int x){return x%3 == 0;}); counter13 = std::count_if(arr1.begin(), arr1.end(), [](int x){return x%13 == 0;}); cout << counter3 << " " << counter13 << endl; //Lambda表达式 counter3 = counter13 = 0; auto mod3 = [](int x){return x%3 == 0;}; auto mod13 = [](int x){return x%13 == 0;}; counter3 = std::count_if(arr1.begin(), arr1.end(), mod3); counter13 = std::count_if(arr1.begin(), arr1.end(), mod13); cout << counter3 << " " << counter13 << endl; //Lambda 传引用 counter3 = counter13 = 0; for_each(arr1.begin(), arr1.end(), [&counter3](int x){counter3 += (x%3 == 0);}); for_each(arr1.begin(), arr1.end(), [&counter13](int x){counter13 += (x%13 == 0);}); cout << counter3 << " " << counter13 << endl; counter3 = counter13 = 0; for_each(arr1.begin(), arr1.end(), [&](int x){counter3 += (x%3 == 0); counter13 += (x%13 == 0);}); cout << counter3 << " " << counter13 << endl; // vector<int> arr1(7); // vector<int> arr2(7); // vector<int> arr3(7); // // cout << endl; // cout << "arr1:\t"; // for_each(arr1.begin(), arr1.end(), // [](int x){std::cout.width(6); std::cout << x << ' ';} // ); // cout << endl; // cout << "arr2:\t"; // for_each(arr2.begin(), arr2.end(), // [](int x){std::cout.width(6); std::cout << x << ' ';} // ); // cout << endl; // cout << "arr3:\t"; // for_each(arr3.begin(), arr3.end(), // [](int x){std::cout.width(6); std::cout << x << ' ';} // ); return 0; }
常记溪亭日暮,沉醉不知归路。兴尽晚回舟,误入藕花深处。争渡,争渡,惊起一滩鸥鹭。
昨夜雨疏风骤,浓睡不消残酒。试问卷帘人,却道海棠依旧。知否?知否?应是绿肥红瘦。
【推荐】国内首个AI IDE,深度理解中文开发场景,立即下载体验Trae
【推荐】编程新体验,更懂你的AI,立即体验豆包MarsCode编程助手
【推荐】抖音旗下AI助手豆包,你的智能百科全书,全免费不限次数
【推荐】轻量又高性能的 SSH 工具 IShell:AI 加持,快人一步
· TypeScript + Deepseek 打造卜卦网站:技术与玄学的结合
· 阿里巴巴 QwQ-32B真的超越了 DeepSeek R-1吗?
· 【译】Visual Studio 中新的强大生产力特性
· 【设计模式】告别冗长if-else语句:使用策略模式优化代码结构
· 10年+ .NET Coder 心语 ── 封装的思维:从隐藏、稳定开始理解其本质意义
2018-04-24 MPSK 调制信号的产生