C++11之lambda(二)

1、仿函数

        仿函数(functor),即使一个类使用上看上去像函数。其实现就是类中实现一个operator(),这个类就有了类似函数的行为,就是一个仿函数类。

仿函数的作用:

        有时仿函数的使用是为了函数拥有类的性质,以达到安全传递函数指针,依据函数生成对象,甚至是让函数之间有继承关系,对函数进行运算和操作的效果。

例:

struct MyPlus{
    int operator()(const int &a , const int &b) const{
        return a + b;
    }
};

int main()
{
    MyPlus a;
    cout << MyPlus()(1,2) << endl;        //1、通过产生临时对象调用重载运算符
    cout << a.operator()(1,2) << endl;    //2、通过对象显示调用重载运算符
    cout << a(1,2) << endl;               //3、通过对象类似函数调用 隐示地调用重载运算符
    return 0;
}

 

2、lambda表达式是对象不是类型

        编译器在实现lambda时,将其转化为函数对象(仿函数functor)。仿函数和 Lambda 表达式是可以有状态的,也就是说它们可以含数据成员,而函数指针就无状态可言,比如下面这种情况就无法用函数指针,只能用仿函数或 Lambda 表达式。

例:

#include <iostream>
#include <vector>
#include <algorithm>

using namespace std;

void printWithLambda(const vector<int> &vec, int standard)
{
	for_each(vec.begin(), vec.end(), [standard] (int elem) {
		if (elem > standard)
		{
			cout << elem << " ";
		}
	});
}

struct Printor
{
public:
	Printor(int standard) :_standard(standard) {}
	void  operator()(int elem)const {
		if (elem > _standard)
		{
			cout << elem << " ";
		}
	}

private:
	int _standard;
};

void printWithFunctor(const vector<int> &vec, int standard)
{
	for_each(vec.begin(), vec.end(), Printor(standard));
}

int main()
{
	int arr[] = { 5, 4, 6, 8, 1 };
	int size = sizeof arr / sizeof *arr;
	vector<int> vec(arr, arr + size);

	cout << "输出最小的数:" << endl;
	int standard;
	cin >> standard;

	printWithFunctor(vec, standard);
	cout << endl;
	printWithLambda(vec, standard);
	cout << endl;

	system("pause");
	return 0;
}

输出:

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值