内容参考于《21天学通C++》(第八版)
八.lambda函数(匿名函数)
1. 示例
#include <iostream>
#include <vector>
using namespace std;
void ForEach(const std::vector<int> &values, void(*func)(int))
{
for (int value : values)
func(value);
}
int main(int argc, char const *argv[])
{
std::vector<int> values = { 1, 2, 3, 2, 1 };
ForEach(values, [](int value) { std::cout << "value: " << value << std::endl; });
std::cin.get();
}
运行结果
value: 1
value: 2
value: 3
value: 2
value: 1
2. 作用
刚开始我一直不懂lambda是啥,知道有人告诉我就是匿名函数,瞬间秒懂。一个没有函数名的函数,可以直接作为参数传入。
/* 这是一个没有函数名的函数,可以直接作为参数传入 */
[](int value) { std::cout << "value: " << value << std::endl; }
[](int value)
{
std::cout << "value: " << value << std::endl;
}