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; }
常记溪亭日暮,沉醉不知归路。兴尽晚回舟,误入藕花深处。争渡,争渡,惊起一滩鸥鹭。
昨夜雨疏风骤,浓睡不消残酒。试问卷帘人,却道海棠依旧。知否?知否?应是绿肥红瘦。