C++ 仿函数(一)

目录

一、仿函数是什么?

二、仿函数的特点

1.仿函数在使用时,可以像普通函数那样调用, 可以有参数,可以有返回值

2.仿函数超出普通函数的概念,可以有自己的状态

​编辑3.仿函数可以作为参数传递。

三、谓词

一元谓词示例:

二元谓词示例:

总结

一、仿函数是什么?

        仿函数也叫函数对象,是定义了一个含有operator()成员函数的对象,可以视为一个一般的函数,只不过这个函数功能是在一个类中的运算符operator()中实现,它将函数作为参数传递的方式来使用。

二、仿函数的特点

1.仿函数在使用时,可以像普通函数那样调用, 可以有参数,可以有返回值

class MyAdd
{
public:
	int operator()(int v1, int v2)
	{
		return v1 + v2;
	}
};

//1.函数对象在使用时,可以像普通函数那样调用,可以有参数和返回值
void test01()
{
	MyAdd myAdd;
	cout << myAdd(1, 2) << endl;
}

 结果输出:3

2.仿函数超出普通函数的概念,可以有自己的状态

//2、函数对象可以有自己的状态
class MyPrint
{
public:
	MyPrint()
	{
		count = 0;
	}
	void operator()(string test)
	{
		cout << test << endl;
		count++; //统计使用次数
	}

	int count; //内部自己的状态
};
void test02()
{
	MyPrint myPrint;
	myPrint("hello world");
	myPrint("hello world");
	myPrint("hello world");
	cout << "myPrint调用次数为: " << myPrint.count << endl;
}

运行结果:


3.仿函数可以作为参数传递。

//3、函数对象可以作为参数传递
void doPrint(MyPrint& mp, string test)
{
	mp(test);
}

void test03()
{
	MyPrint myPrint;
	doPrint(myPrint, "Hello C++");
}

 运行结果:

优点:
        1.仿函数可有拥有自己的数据成员和成员变量,比一般函数灵活。
        2.仿函数比函数指针的执行速度快。
        3.仿函数可以作为模板参数使用,因为每个仿函数都拥有自己的类型。

缺点:
        1.需要单独实现一个类。
        2.定义形式比较复杂。

三、谓词

仿函数返回值类型是bool数据类型,称为谓词

如果operator接受一个参数,那么称为一元谓词;如果接受两个参数,那么称为二元谓词

一元谓词示例:

//1.一元谓词 参数中只有一个的谓词,称为一元谓词
struct GreaterFive {
	bool operator()(int val) {
		return val > 15;
	}
};

void test01() {

	vector<int> v;
	for (int i = 0; i < 10; i++)
	{
		v.push_back(i);
	}
	//查找容器中有没有大于5的数字
	//GreateFive(),匿名函数对象
	vector<int>::iterator it = find_if(v.begin(), v.end(), GreaterFive());
	if (it == v.end()) {
		cout << "没找到!" << endl;
	}
	else {
		cout << "找到:" << *it << endl;
	}

}

 因为我们设置的vector容器中的数是0-9,所以无法找到15,故输出“没找到”

二元谓词示例:

//二元谓词
class MyCompare
{
public:
	bool operator()(int num1, int num2)
	{
		return num1 > num2;
	}
};


void test02()
{
	vector<int> v;
	v.push_back(1);
	v.push_back(2);
	v.push_back(5);
	v.push_back(7);
	v.push_back(9);

	//默认从小到大
	sort(v.begin(), v.end());
	for (vector<int>::iterator it = v.begin(); it != v.end(); it++)
	{
		cout << *it << " ";
	}
	cout << endl;
	cout << "----------------------------" << endl;

	//使用函数对象改变算法策略,排序从大到小
	sort(v.begin(), v.end(), MyCompare());
	for (vector<int>::iterator it = v.begin(); it != v.end(); it++)
	{
		cout << *it << " ";
	}
	cout << endl;
}

运行结果:

 

总结

        本文让我们对仿函数有了初步的认识,知道了什么是仿函数,仿函数的优缺点还有什么是谓词。

  • 1
    点赞
  • 5
    收藏
    觉得还不错? 一键收藏
  • 打赏
    打赏
  • 0
    评论

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

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

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

打赏作者

小梁今天敲代码了吗

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

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

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

打赏作者

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

抵扣说明:

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

余额充值