STL之仿函数

仿函数,也可以称为函数对象,实则是一个类,重载了(),调用方便,十分灵活。

#include<iostream>
using namespace std;
#include<vector>
#include<algorithm>
#include<functional>
class base
{
public:
	base()
	{
		this->count = 0;
	}
	int operator()(int a,int b)
	{
		return a + b;
	}
	//一元谓词
	bool operator()(int value)
	{
		return value > 8;
	}
	void operator()(string test)
	{
		cout << test << endl;
		count++;
	}
	int count;

};
class Compare
{
public:
	//二元谓词
	bool operator()(int a, int b)
	{
		return a > b;
	}
};
void print(base &b,string s)
{
	b(s);//相当于b.operator()(s);
}
void test1()
{
	base b;
	print(b,"hello world!");//调用了上面的b(s);函数而这个函数调用了operator()(string test),函数对象的特点,可以作为参数传递
}
void test2()
{
//函数对象的讲解
	base b;
	b("gg");//强大在于,不用再写输出语句,在初始化的同时就实现了输出,自动调用了operator()函数
	cout << "函数调用的次数为:" << b.count << endl;
}
void test3()
{
	base b;
	cout << b(10, 20) << endl;
}
void test4()
{
	vector<int>v;
	for (int i = 0; i < 10; i++)
	{
		v.push_back(i);
	}
	//base b;非匿名对象创建参数
	vector<int>::iterator result = find_if(v.begin(), v.end(), base());//find_if会输出找到后的第一个元素,不会把剩下的元素都打印输出,第三个参数为谓词,且是一元谓词,且重载的函数类型必须要是bool型,这里采用了匿名对象的方式创建了第三个参数
	if (result != v.end())
	{
		cout << "找到了且为:" << *result << endl;
	}
	else
	{
		cout << "未找到!" << endl;
	}
}
void print(vector<int>&v)
{
	for (vector<int>::iterator it = v.begin(); it != v.end(); it++)
	{
		cout << *it << endl;
	}
}
void test5()
{
	vector<int>v;
	v.push_back(11);
	v.push_back(21);
	v.push_back(31);
	v.push_back(41);
	v.push_back(51);
	sort(v.begin(), v.end());//先进行升序
	print(v);
	//sort(v.begin(),v.end(),Compare());
	//下面的代码和上面的代码含义相同,功能一样,一个是用自己提供的仿函数,一个是用STL提供的仿函数
	sort(v.begin(), v.end(), greater<int>());//第三个参数,记得包含头文件,且是模板化参数列表,这里是匿名对象的创建使用,实现降序排列
	cout << "降序排列为:" << endl;
	print(v);
}
//STL提供的仿函数
void test6()
{
	negate<int>n;
	cout << n(50) << endl;//取反
	plus<int>p;
	cout << p(10, 20) << endl;//返回和
	minus<int>m1;//相减操作
	cout << m1(50, 30) << endl;
	multiplies<int>m2;//乘法
	cout<<m2(6, 6)<<endl;
	divides<int>d;//除法操作
	cout << d(8, 4) << endl;
	modulus<int>m3;//取模操作
	cout<<m3(8, 4)<<endl;
}
int main()
{
	//test1();
	//test2();
	//test3();
	//test4();
	//test5();
	test6();
	system("pause");
	return 0;
}

代码就以上了,注释都在代码后面,我就不再赘述了,强调一下,要是要用STL的仿函数,一定要包含头文件functional,这样就可以使用了,一定要记得模板化参数,还有就是,那个是二元谓词,那个参数是一元谓词,bool类型很关键!!!代码一定要亲自动手,不要看一遍就过了,自己打出来的才是你自己的知识!!!

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

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

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

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

打赏作者

潜渊@龙

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

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

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

打赏作者

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

抵扣说明:

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

余额充值