C++ lambda表达式 (二)
2024-08-31 15:17:27
#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;
}
可以看到i是拷贝值,j是引用值,所以是24,结果26
把lambda表达式当作参数传送
#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();
numbers.push_back();
numbers.push_back();
numbers.push_back();
numbers.push_back(); // 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 % ) == ; });//查找第一个偶数 // 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;
}
}
lambda表达式嵌套使用
#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 * ; }(x) + ; }(); // Print the result.
cout << timestwoplusthree << endl;
}
ambda表达式使用在高阶函数里
#include <iostream>
#include <functional> int main()
{
using namespace std; auto addtwointegers = [](int x) -> function<int(int)> {
return [=](int y) { return x + y; };
}; auto higherorder = [](const function<int(int)>& f, int z) {
return f(z) * ;
}; // Call the lambda expression that is bound to higherorder.
auto answer = higherorder(addtwointegers(), ); // Print the result, which is (7+8)*2.
cout << answer << endl;
}
最新文章
- SqlServer -- char与varchar、nchar、N
- Qt 程序访问 sqlite 权限错误
- NYOJ题目1102Fibonacci数列
- cer pfx格式数字证书区别
- jQuery Mobile 移动开发中的日期插件Mobiscroll使用说明
- ADO.NET——获取output 和 return值
- (四)值栈与OGNL
- iOS数组、字典与json字符串的转换
- FPGA中浮点运算实现方法——定标
- nginx做反向负载均衡,后端服务器获取真实客户端ip
- C++对象模型之lambda表达式
- plsql developer 中文乱码(???)解决办法
- Python3 与 Python2 的不同
- Spark MLlib线性回归代码实现及结果展示
- spring中整合memcached,以及创建memcache的put和get方法
- Nginx referer防盗链模块
- 内核futex的BUG导致程序hang死问题排查
- Lower Power with CPF(二)
- PHP 笔记——自定义函数
- Windows7 64bits下安装TensorFlow CPU版本(图文详解)