C++STL总结笔记(二)——仿函数(函数对象)

文章目录


一、概念

仿函数又称函数对象,即重载了函数调用运算符()的类的对象。
优势:
1.仿函数对象的内部可以有自己的状态,可以实现一些其他的功能。
2.函数对象可以作为参数进行传递。

当仿函数类内重载的返回值是bool类型被称为谓词,形参为1个为1元谓词,2个是2元谓词。

class Compare
{
public:
	Compare()
	{
		n = 0;
	}
	//一元谓词
	bool operator()(int a)
	{
		n++;
		return a > 5;	
	}
    //二元谓词
	bool operator()(int a, int b)
	{
		n++;
		return a > b;	
	}
	int n;
};

bool Print(Compare& c, int a, int b)
{
	return c(a, b);
}

int main()
{
	Compare c;//函数对象
	//调用重载()
	cout << c(1, 2) << endl;
	cout << c(3, 2) << endl;
	cout << c(2, 1) << endl;
	//可实现计数功能
	cout << c.n << endl;

	//作为参数传递
	cout << Print(c, 3, 6) << endl;
	
	system("pause");
}
0
1
1
3
0

STL里内置了一些仿函数类型,包括算术仿函数、关系仿函数、逻辑仿函数。

算数仿函数包括+,-,*,/, 取模,取反。

#include<iostream>
#include<string>
#include<functional>//STL内部函数对象头文件
using namespace std;

int main()
{
	//算术仿函数

	//加法
	plus<int>a;
	cout << a(1, 2) << endl;

	//减法
	minus<int>a1;
	cout << a1(1, 2) << endl;

	//乘法
	multiplies<int>a2;
	cout << a2(1, 2) << endl;

	//除法
	divides<int>a3;
	cout << a3(2, 1) << endl;

	//取反仿函数
	negate<int>b;

	cout << b(1) << endl;

	//取模仿函数
	modulus<int>c;
	cout << c(3,2) << endl;

	system("pause");
}
3
-1
2
2
-1
1

关系仿函数包括>,<,=,<=,>=,!=。

#include<iostream>
#include<string>
#include<list>
#include<functional>//STL内部函数对象头文件
using namespace std;


int main()
{
	list<int>L;


	//插入
	L.push_back(1);
	L.push_back(2);


	list<int>L1;
	L1 = L;

	//内置的关系仿函数,大于
	//L.sort(greater<int>());
	//小于
	//L.sort(less<int>());
	//小于等于
	L.sort(greater_equal<int>());

	for (list<int>::iterator i = L.begin(); i != L.end(); i++)
	{
		cout << *i <<  endl;
	}

	system("pause");
}

逻辑运算符包括与或非。

	list<bool>L1;
	L1.push_back(true);
	L1.push_back(false);

	for (list<bool>::iterator i = L1.begin(); i != L1.end(); i++)
	{
		cout << *i << endl;
	}

	list<bool>L2;
	L2.resize(L1.size());

	transform(L1.begin(), L1.end(), L2.begin(),logical_not<bool>());
	for (list<bool>::iterator i = L2.begin(); i != L2.end(); i++)
	{
		cout << *i << endl;
	}

总结

对于简单的容器之间的运算可以使用内置的仿函数,如果想自定义更复杂的仿函数,就需要自己构建仿函数类。

  • 3
    点赞
  • 1
    收藏
    觉得还不错? 一键收藏
  • 2
    评论

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

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

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值