C++_函数对象(仿函数)_学习笔记

1 函数对象基本概念

  1. 函数对象在使用时可以向普通函数那样调用,可以有参数和返回值。
class myadd
{
public:
	int operator()(int a, int b)
	{
		return a + b;
	}
};
void test()
{
	int a = 5;
	int b = 6;
	myadd ma;
	cout << ma(a, b) << endl;
}
  1. 函数对象可以有自己的状态。
class myPrint
{
public:
	myPrint()
	{
		this->count = 0;
	}
	void operator()(string test)
	{
		cout << test << endl;
		count++;
	}
	int count;
};
void test()
{
	myPrint mp;
	string str = "hello";
	mp(str);
	cout << mp.count << endl;
}

以上函数对象中有一个状态count,可以访问他。这在普通的函数中是没有的。
3. 函数对象可以作为参数传递。

class myPrint
{
public:
	myPrint()
	{
		this->count = 0;
	}
	void operator()(string test)
	{
		cout << test << endl;
		count++;
	}
	int count;
};
void doPrint(myPrint& mp, string test)
{
	mp(test);
}
void test()
{
	myPrint mp;
	doPrint(mp, "Hello");
	
}

2 谓词

返回bool的仿函数称为谓词
operator()接收一个参数叫一元谓词,两个叫二元谓词。
以下代码构建了一个仿函数,返回bool值,实现查找功能。

class Bigger5
{
public:
	bool operator()(int val)
	{
		return val > 5;
	}
};

void test()
{
	vector<int>v;
	for (int i = 0; i < 10; i++)
	{
		v.push_back(i);
	}
	//查找有没有大于5的
	vector<int>::iterator it = find_if(v.begin(), v.end(), Bigger5());
	if (it == v.end())
	{
		cout << "没找到" << endl;
	}
	else {
		cout << "找到了" << endl;
	}
	
}

3 内建函数对象

STL内建了一些函数对象:算数仿函数、关系仿函数、逻辑仿函数。

3.1 算数仿函数:实现四则运算

plus // 加法
minus // 减法
multiplies // 乘法
divides // 除法
modulus // 取模
negat //取反
#include<functional>

plus<int>p;
cout << p(25,15) << endl;

negate<int>n; // 取反
cout << n(50) << endl;

3.2 关系仿函数:实现关系对比

返回bool

equal_to // 等于
not_equal_to // 不等于
greater // 大于
greater_equal // 大于等于
less // 小于
less_equal // 小于等于

可以使用内建函数对象进行降序排列

sort(v.begin(), v.end());//升序排序
sort(v.begin(), v.end(), greater<int>());//倒序排序

3.3 逻辑仿函数:实现与或非逻辑运算

返回bool

logical_and
logical_or
logical_not

利用transform搬运v到v2中并取反

transform(v.begin(), v.end(), v2.begin(),v2.begin(), logical_not<bool>())
  • 3
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 1
    评论
评论 1
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值