lambda表达式,for_each、find_if简介

#include <iostream>
#include <future>
#include <vector>
#include <map>
#include <functional>
#include <string>
#include <algorithm>

using namespace std;

class Demo
{
private:
	int m_i=5;
public:
	void myFunc(int i = 3, int j = 4)
	{
		auto func = [=,&i]() 
		{
			i=3;
			j;

			m_i = 12;

			return m_i; 
		};

		cout << func() << endl;
	}
};

void myfunc(int i)
{
	cout << i << endl;
}

int main()
{
	Demo d;

	//d.myFunc();

	int x = 5;
	auto func = [=]() mutable {

		x = 6;

		return x;
	};

	x = 10;

	std::function<int(int)> fc1 = [](int tv) {return tv; };

	cout << fc1(15) << endl;

	//std::bind 第一个参数是函数指针(可调用对象),第二个参数开始才是真正的函数参数
	std::function<int(int)> fc2 = std::bind([](int tv) {return tv; }, 16);

	cout << fc2(678) << endl; //不管fc2参数是多少,都会输出16,因为bind的第二个参数绑定16。

	//不捕获任何变量的 lambda表达式,也就是捕获列表为空,可以转换成一个普通的函数指针。

	using functype = int(*)(int);
	functype fp = [](int tv) {return tv; };

	cout << fp(20) << endl;

	//(5.1)语法糖概念:一种便捷写法
	int a[5];
	a[1] = 3; // 等价与 *(a+1)=3;


	//六
	//for_each 是一个函数模板;
	cout << endl;

	vector<int> myvector = {10,20,30,40,50};
	for_each(myvector.begin(), myvector.end(), myfunc);

	int isnum = 0;
	for_each(myvector.begin(), myvector.end(), [&isnum](int val) {isnum += val; });
	cout << "isnum = " << isnum << endl;

	//find_if 是一个函数模板;
	cout << endl;

	auto res = find_if(myvector.begin(), myvector.end(), [](int val) {
		cout << val << endl; 
		return false; //只要返回为false,那么find_if就不停的遍历myvector,一直到返回true或者遍历完为止。
		});

	cout << endl;

	auto res1 = find_if(myvector.begin(), myvector.end(), [](int val) {
		cout << val << endl;
		return (2*val > 50); //只要返回为false,那么find_if就不停的遍历myvector,一直到返回true或者遍历完为止。
		});

	if (res1 == myvector.end())
	{
		cout << "没有找到满足条件的对应的元素" << endl;
	}
	else
	{
		cout << "找到对应满足条件的元素:" << *res1<< endl;
	}

	return 0;
}

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 打赏
    打赏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包

打赏作者

repinkply

你的鼓励将是我创作的最大动力

¥1 ¥2 ¥4 ¥6 ¥10 ¥20
扫码支付:¥1
获取中
扫码支付

您的余额不足,请更换扫码支付或充值

打赏作者

实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

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

余额充值