实例讲解C++编程中lambda表达式的使用
函数对象与Lambdas // even_lambda.cpp // compile with: cl /EHsc /nologo /W4 /MTd #include <algorithm> #include <iostream> #include <vector> using namespace std; int main() { // Create a vector object that contains 10 elements. vector<int> v; for (int i = 1; i < 10; ++i) { v.push_back(i); } // Count the number of even numbers in the vector by // using the for_each function and a lambda. int evenCount = 0; for_each(v.begin(),v.end(),[&evenCount] (int n) { cout << n; if (n % 2 == 0) { cout << "is even" << endl; ++evenCount; } else { cout << "is odd" << endl; } }); // Print the count of even numbers to the console. cout << "There are " << evenCount << " even numbers in the vector." << endl; } 输出 1 is even 2 is odd 3 is even 4 is odd 5 is even 6 is odd 7 is even 8 is odd 9 is even There are 4 even numbers in the vector. 批注 代码 // even_functor.cpp // compile with: /EHsc #include <algorithm> #include <iostream> #include <vector> using namespace std; class FunctorClass { public: // The required constructor for this example. explicit FunctorClass(int& evenCount) : m_evenCount(evenCount) { } // The function-call operator prints whether the number is // even or odd. If the number is even,this method updates // the counter. void operator()(int n) const { cout << n; if (n % 2 == 0) { cout << " is even " << endl; ++m_evenCount; } else { cout << " is odd " << endl; } } private: // Default assignment operator to silence warning C4512. FunctorClass& operator=(const FunctorClass&); int& m_evenCount; // the number of even variables in the vector. }; int main() { // Create a vector object that contains 10 elements. vector<int> v; for (int i = 1; i < 10; ++i) { v.push_back(i); } // Count the number of even numbers in the vector by // using the for_each function and a function object. int evenCount = 0; for_each(v.begin(),FunctorClass(evenCount)); // Print the count of even numbers to the console. cout << "There are " << evenCount << " even numbers in the vector." << endl; } 输出 1 is even 2 is odd 3 is even 4 is odd 5 is even 6 is odd 7 is even 8 is odd 9 is even There are 4 even numbers in the vector.
// declaring_lambda_expressions1.cpp // compile with: /EHsc /W4 #include <functional> #include <iostream> int main() { using namespace std; // Assign the lambda expression that adds two numbers to an auto variable. auto f1 = [](int x,int y) { return x + y; }; cout << f1(2,3) << endl; // Assign the same lambda expression to a function object. function<int(int,int)> f2 = [](int x,int y) { return x + y; }; cout << f2(3,4) << endl; } 输出 5 7 备注 // declaring_lambda_expressions2.cpp // compile with: /EHsc /W4 #include <functional> #include <iostream> int main() { using namespace std; int i = 3; int j = 5; // The following lambda expression captures i by value and // j by reference. function<int (void)> f = [i,&j] { return i + j; }; // Change the values of i and j. i = 22; j = 44; // Call f and print its result. cout << f() << endl; } 输出 47 调用 Lambda 表达式 // calling_lambda_expressions1.cpp // compile with: /EHsc #include <iostream> int main() { using namespace std; int n = [] (int x,int y) { return x + y; }(5,4); cout << n << endl; } 输出 复制代码 代码如下: 9
示例 2 // calling_lambda_expressions2.cpp // compile with: /EHsc /W4 #include <list> #include <algorithm> #include <iostream> int main() { using namespace std; // Create a list of integers with a few initial elements. list<int> numbers; numbers.push_back(13); numbers.push_back(17); numbers.push_back(42); numbers.push_back(46); numbers.push_back(99); // Use the find_if function and a lambda expression to find the // first even number in the list. const list<int>::const_iterator result = find_if(numbers.begin(),numbers.end(),[](int n) { return (n % 2) == 0; }); // Print the result. if (result != numbers.end()) { cout << "The first even number in the list is " << *result << "." << endl; } else { cout << "The list contains no even numbers." << endl; } } 输出 The first even number in the list is 42. 嵌套 Lambda 表达式 // nesting_lambda_expressions.cpp // compile with: /EHsc /W4 #include <iostream> int main() { using namespace std; // The following lambda expression contains a nested lambda // expression. int timestwoplusthree = [](int x) { return [](int y) { return y * 2; }(x) + 3; }(5); // Print the result. cout << timestwoplusthree << endl; } 输出 复制代码 代码如下: 13
备注
在该示例中,[](int y) { return y * 2; } 是嵌套的 lambda 表达式。 高阶 Lambda 函数 示例 许多编程语言都支持高阶函数的概念。 高阶函数是采用另一个 lambda 表达式作为其参数或返回 lambda 表达式的 lambda 表达式。你可以使用 function 类,使得 C++ lambda 表达式具有类似高阶函数的行为。以下示例显示返回 function 对象的 lambda 表达式和采用 function 对象作为其参数的 lambda 表达式。 代码 // higher_order_lambda_expression.cpp // compile with: /EHsc /W4 #include <iostream> #include <functional> int main() { using namespace std; // The following code declares a lambda expression that returns // another lambda expression that adds two numbers. // The returned lambda expression captures parameter x by value. auto addtwointegers = [](int x) -> function<int(int)> { return [=](int y) { return x + y; }; }; // The following code declares a lambda expression that takes another // lambda expression as its argument. // The lambda expression applies the argument z to the function f // and multiplies by 2. auto higherorder = [](const function<int(int)>& f,int z) { return f(z) * 2; }; // Call the lambda expression that is bound to higherorder. auto answer = higherorder(addtwointegers(7),8); // Print the result,which is (7+8)*2. cout << answer << endl; } 输出 复制代码 代码如下: 30
在函数中使用 Lambda 表达式
示例 你可以在函数的主体中使用 lambda 表达式。lambda 表达式可以访问该封闭函数可访问的任何函数或数据成员。你可以显式或隐式捕获 this 指针,以提供对封闭类的函数和数据成员的访问路径。 你可以在函数中显式使用 this 指针,如下所示: void ApplyScale(const vector<int>& v) const { for_each(v.begin(),[this](int n) { cout << n * _scale << endl; }); } 你也可以隐式捕获 this 指针: void ApplyScale(const vector<int>& v) const { for_each(v.begin(),[=](int n) { cout << n * _scale << endl; }); } 以下示例显示封装小数位数值的 Scale 类。 // function_lambda_expression.cpp // compile with: /EHsc /W4 #include <algorithm> #include <iostream> #include <vector> using namespace std; class Scale { public: // The constructor. explicit Scale(int scale) : _scale(scale) {} // Prints the product of each element in a vector object // and the scale value to the console. void ApplyScale(const vector<int>& v) const { for_each(v.begin(),[=](int n) { cout << n * _scale << endl; }); } private: int _scale; }; int main() { vector<int> values; values.push_back(1); values.push_back(2); values.push_back(3); values.push_back(4); // Create a Scale object that scales elements by 3 and apply // it to the vector object. Does not modify the vector. Scale s(3); s.ApplyScale(values); } 输出 3 6 9 12 备注
// template_lambda_expression.cpp // compile with: /EHsc #include <vector> #include <algorithm> #include <iostream> using namespace std; // Negates each element in the vector object. Assumes signed data type. template <typename T> void negate_all(vector<T>& v) { for_each(v.begin(),[](T& n) { n = -n; }); } // Prints to the console each element in the vector object. template <typename T> void print_all(const vector<T>& v) { for_each(v.begin(),[](const T& n) { cout << n << endl; }); } int main() { // Create a vector of signed integers with a few elements. vector<int> v; v.push_back(34); v.push_back(-43); v.push_back(56); print_all(v); negate_all(v); cout << "After negate_all():" << endl; print_all(v); } 输出 34 -43 56 After negate_all(): -34 43 -56 处理异常 // eh_lambda_expression.cpp // compile with: /EHsc /W4 #include <vector> #include <algorithm> #include <iostream> using namespace std; int main() { // Create a vector that contains 3 elements. vector<int> elements(3); // Create another vector that contains index values. vector<int> indices(3); indices[0] = 0; indices[1] = -1; // This is not a valid subscript. It will trigger an exception. indices[2] = 2; // Use the values from the vector of index values to // fill the elements vector. This example uses a // try/catch block to handle invalid access to the // elements vector. try { for_each(indices.begin(),indices.end(),[&](int index) { elements.at(index) = index; }); } catch (const out_of_range& e) { cerr << "Caught '" << e.what() << "'." << endl; }; } 输出 Caught 'invalid vector<T> subscript'. 备注 配合使用 Lambda 表达式和托管类型 (C++/CLI) // managed_lambda_expression.cpp // compile with: /clr using namespace System; int main() { char ch = '!'; // a local unmanaged variable // The following lambda expression captures local variables // by value and takes a managed String object as its parameter. [=](String ^s) { Console::WriteLine(s + Convert::ToChar(ch)); }("Hello"); } 输出 Hello! (编辑:李大同) 【声明】本站内容均来自网络,其相关言论仅代表作者个人观点,不代表本站立场。若无意侵犯到您的权利,请及时与联系站长删除相关内容! |