c++ 11 数组 和lambda表达式 语法 / 函数包装器 基本用法


//倒叙遍历数组并输出 

// []里面的变量可以当做返回值来理解 (int x) 这里就是每次迭代器的值,也就是数组的元素的值

void main()
{
	array<int, 5> arr = { 1,2,3,4,5 };
	int a = 0;
	std::for_each(arr.rbegin(), arr.rend(), [&a](int x) { a = x; cout << a; });
	system("pause");
}


///lambda表达式遍历二维数组

void main()
{
	array<int, 5> arr = { 1,2,3,4,5 };
	array<array<int, 5>, 3> arr1 = { arr,arr,arr };
	int a = 0;
	std::for_each(arr1.rbegin(), arr1.rend(), [&a](array<int, 5> arr2)  
	{
		for_each(arr2.rbegin(), arr2.rend(), [](int x) {cout << x << endl; }); //如果实现累加[&a] a+=x即可
	}
	);
	system("pause");
}



函数包装器基本用法

template<typename T, typename F>

T run(T a, T b, F f)
{
	return f(a, b);
}


 
int test(int a, int b)
{
	return a + b;
}

double test1(double a, double b)
{
	return a + b;
}
 
std::function<int(int, int)> func;
std::function<double(double, double)> func1;
void main()
{
	func = test;
	func1 = test1;
	cout << run(1, 2, func) << endl;
	cout << run(1.2, 2.0, func1)<<endl;
	cout << run(1, 2, test) << endl;
	cout << run(1.2, 2.0, test1);
	system("pause");
}


  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值