许多编程语言支持匿名函数的概念,这些函数有函数体,但是没有函数名。 lambda是与匿名函数相关的编程技术。 lambda 隐式定义函数对象类和构造函数对象。选件类类型。
此示例使用在 for_each 嵌入函数调用打印到控件中的 lambda 在 vector 对象的每个元素是否均匀或更多的。
代码
// 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 = 0; 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; }
Output
0 is even 1 is odd 2 is even 3 is odd 4 is even 5 is odd 6 is even 7 is odd 8 is even 9 is odd There are 5 even numbers in the vector.
注释
在此示例中,for_each 函数的第三个参数是一个lambda。 [&evenCount] 部件来指定表达式中获取子句,(int n) 指定参数,因此,其余部分来指定表达式的主体。
有时 lambda 比前面大麻烦的以致无法扩展进一步。 下一个示例使用函数对象而不是 lambda,与 for_each 功能外,还生成结果和示例 1. 相同。 两个示例在 vector对象存储计数偶数。 若要维护操作的状态,FunctorClass 选件类存储 m_evenCount 变量引用作为成员变量。 若要执行操作,FunctorClass 实现函数调用运算符,operator()。 Visual C++ 编译器生成与示例 1. 中的 lambda 代码的大小是可比的和性能的代码。 对于基本的问题比函数对象模型 (如一个本文中,更简单的 lambda 模型可能好。 但是,因此,如果您认为功能可能在将来需要大量展开,然后使用函数对象模型,以便代码维护会更加容易。
有关 operator() 的更多信息,请参见函数调用(C++)。 有关 for_each 函数的更多信息,请参见 for_each。
代码
// 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 = 0; 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(), v.end(), FunctorClass(evenCount)); // Print the count of even numbers to the console. cout << "There are " << evenCount << " even numbers in the vector." << endl; }