C++lambdas

什么是lambdas表达式?

答:lambdas是函数对象,当我们编写了一个lambdas后,编译器会将该表达式翻译成一个未命名类的未命名对象(仿函数对象)

//lambdas完整形式写法
[]()mutable throw()-> retType{}

// []  ----- 捕获列表
// ()  ----- 参数列表  
// mutable  -----表示捕获列表里的参数可以改变 
// throw() -------抛出异常
// ->retType  ------返回类型
// {} ---------函数体
//使用例子
class Functor
{
private:
	int id;
public:
	Functor(int ID) :id(ID) {}
	void operator()()
	{
		cout << id << endl;
		++id;
	}
};

int main()
{ 
    //lambdas用法
	int id = 0;
	//等价于生成上述仿函数的对象----即 Functor fx(id)
	auto fx = [id]()mutable {cout << id << endl;  ++id; }; 	
	//注意:如果mutable去掉函数体内不可修改id的值
	id = 42;
	fx();
	cout << id << endl;
	fx();
	
   //上述等价于下面的用法
	cout << endl;
	id = 0;
	Functor f(id);
	id = 42;
	f();
	cout << id<<endl;
	f();	
}

注意: Functor f(id) 生成一个 f 函数对象 id初始化其状态,之后f()为函数调用,()为函数参数列表

lambdas的捕获列表by value 和by reference

int main()
{
	int a = 1,b=1;
	//a:by value    b:by reference
	auto f = [a, &b]()mutable->void { a += 5; b += 5; };
	f();
	cout << "a:" << a <<endl<< "b:" << b << endl;
	//a:1 b:6
}

lambdas与decltype的配合使用

我们都知道如果只有object但不知道它的类型,我们可以采用decltype,lambdas返回的是一个函数对象,有时候我们需要它的类型,就用到了decltype。

class people
{
 public:
	string name;
	int age;
};

int main()
{
	auto cmp = [](const people& p1, const people& p2)->bool { return p1.age > p2.age; };

	set<people, decltype(cmp)>P(cmp);  //set的排序准则由人的年龄决定
	
}

lambdas应用于标准库算法

标准库存在许多需要传入仿函数的算法,一般以_if结尾的算法都是该类型

//如何利用remove_if 配合lambdas 删除[4,7]范 围的元素
int main()
{
	vector<int>coll = { 1,2,3,4,5,6,7,8,9,4 };
	
	coll.erase(remove_if(coll.begin(), coll.end(),
	 [](int i)->bool { return      (i>=4&&i<=7); }),coll.end()); 
	
	for (auto e : coll)
		cout << e << ' ';  //输出1 2 3 8 9
}
原创文章 23 获赞 1 访问量 359

猜你喜欢

转载自blog.csdn.net/weixin_44806268/article/details/105734221
C