函数对象

概念

  • 重载函数调用操作符的类,其对象称为函数对象
  • 函数对象使用重载的()时,行为类似函数调用,也叫仿函数

特点

  • 可以像函数一样调用
  • 可以有自己的状态,成员属性
  • 可以像参数一样传递
class MyAdd
{
public:
	int operator()(int v1, int v2)
	{
		return v1 + v2;
	}
};
class Myprint
{
public:
	Myprint()
	{
		this->count = 0;
	}
	int count;
	void operator()(string test)
	{
		cout << test << endl;
		this->count++;
	}
};

void doPrint(Myprint& mp, string test)
{
	mp(test);
}

void test01()
{
	MyAdd myadd;
	cout << myadd(1, 2) << endl;
	Myprint myprint;
	for( int i = 0; i < 10 ; i++)
	{
		myprint("hello world!");
	}
	cout << "the time of calling myprint is: " << myprint.count << endl;
	doPrint(myprint, "Hello, c++!");
}

谓词

一元谓词

  • 返回bool类型的仿函数称为谓词
  • 如果operator()接受一个参数,称为一元谓词;
  • 如果operator()接受两个参数,称为二元谓词;
class GreaterFive
{
public:
	bool operator()(int val)
	{
		return val > 5;
	}
};

void test01()
{
	vector<int> v;
	for (int i = 0; i < 6; i++)
	{
		v.push_back(i);
	}

	vector<int>::iterator it = find_if(v.begin(), v.end(), GreaterFive());
	if (it == v.end())
	{
		cout << "not found" << endl;
	}
	else
	{
		cout << " Find a number bigger than 5: " << *it << endl;
	}
}

二元谓词

class MyCompare
{
public:
	int count;
	class MyCompare()
	{
		this->count = 0;
	}
	bool operator()(int a, int b)
	{
		this->count++;
		return a > b;
	}
};

void test01()
{
	vector<int> v;
	v.push_back(10);
	v.push_back(40);
	v.push_back(20);
	v.push_back(30);
	v.push_back(50);

	sort(v.begin(), v.end());
	printVec<int>(v);
	MyCompare mycompare;
	sort(v.begin(), v.end(), mycompare);
	printVec<int>(v);
}

内建算术仿函数

  • 实现四则运算
  • negate是一元运算,其余是二元运算
#include<functional>

void test01()
{
	negate<int> n;
	cout << n(50) << endl;
	plus<int>p;
	cout << p(2, 3) << endl;
	minus<int> m;
	cout << m(5, 2) << endl;
}

关系仿函数

[外链图片转存失败,源站可能有防盗链机制,建议将图片保存下来直接上传(img-WAyryHeE-1605073301062)(https://i.loli.net/2020/11/10/DmFfnUoM7u4eAGP.png)]

void test01()
{
	vector<int> v;
	v.push_back(1);
	v.push_back(3);
	v.push_back(4);
	v.push_back(3);
	v.push_back(5);
	printVec<int>(v);

	sort(v.begin(), v.end(), greater<int>());
	printVec<int>(v);
}

逻辑仿函数

void test01()
{
	vector<bool> v;
	v.push_back(1);
	v.push_back(0);
	v.push_back(1);
	v.push_back(1);
	v.push_back(0);

	printVec<bool>(v);

	vector<bool> v2;
	v2.resize(v.size());
	transform(v.begin(), v.end(), v2.begin(), logical_not<bool>());
	printVec<bool>(v2);
}
  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

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

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

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值