[C++]STL-函数对象基础知识

函数对象(仿函数)

重载函数调用操作符的类,其对象称为函数对象(function object),即他们是行为类似函数的对象,也叫仿函数(functor),其实就是重载"()"操作符,使得类对象可以像函数那样被调用

注意:

函数对象(仿函数)是一个类,不是一个函数

假定某个类有一个重载的operator(),而且重载的operator()要求获取一个参数,就称其为“一元仿函数(unary functor)”;诸如此类,两个参数即称为二元仿函数等等
#include<iostream>
#include<vector>
#include<algorithm>
using namespace std;




struct MyPrint {
	MyPrint() :num(0) {}
	void operator()(int val) {
		num++;  //记录函数调用次数
		cout << val << endl;
	}
	int num;

};

void FunctorTest1() {
	MyPrint print;
	print(45);   
	
	//函数对象可以像普通函数那样调用
	//函数对象也可以像普通函数那样接入参数
	//函数对象超出了函数的概念,函数对象可以保存函数调用的状态

}

int num = 0;  //真正开发中,尽量避免使用全局变量
//这也是普通函数记录函数调用状态的弊端
void MyPrint2(int val){
	num++;
	cout << val << endl;
}

void FunctorTest2() {
	
	//普通函数计算函数调用次数
	MyPrint2(45);
	MyPrint2(78);
	cout << "MyPrint2()函数调用了:" << num << "次" << endl;
	//函数对象记录函数调用次数,可以避免使用全局变量
	MyPrint print;
	print(445);
	print(99);
	print(781);
	cout << "MyPrint()函数调用了:" << print.num << "次" << endl;
	
	
}


void FunctorTest3() {
	vector<int> v;
	v.push_back(45);
	v.push_back(78);
	v.push_back(12);
	v.push_back(233);
	MyPrint print;
	MyPrint print2 =for_each(v.begin(), v.end(), print);
	cout << "函数调用次数:" << print.num << endl;

	cout << "函数调用次数:" << print2.num << endl;
	//易知print2作为返回值才是调用函数的次数

}


int main() {
	FunctorTest3();

	return 0;
}

谓词概念

谓词是指普通函数或重载的operator()返回值是bool类型的函数对象(仿函数)。如果operator接受一个参数,那么叫做一元谓词,以此类推

内建函数对象

STL 内建了一些函数对象。分为:算数类函数对象,关系运算类函数对象,逻辑运算类仿函数。这些仿函数所产生的对象,用法和一般函数完全相同,当然我们还可以产生无名的临时对象来履行函数功能。使用内建函数对象,需要引入头文件 #include。

6 个算数类函数对象,除了 negate 是一元运算,其他都是二元运算。

template<class T> T plus<T>//加法仿函数
template<class T> T minute<T>//减法仿函数
template<class T> T multiplies<T>//乘法仿函数
template<class T> T divides<T>//除法仿函数
template<class T> T modulus<T>//取模仿函数
template<class T> T negate<T>//取反仿函数

6 个关系运算类函数对象,每一种都是二元运算。

template<class T> bool equal_to<T>//等于
template<class T> bool not_equal_to<T>//不等于
template<class T> bool greater<T>//大于
template<class T> bool greater_equal<T>//大于等于
template<class T> bool less<T>//小于
template<class T> bool less_equal<T>//小于等于

逻辑运算类运算函数,not 为一元运算,其余为二元运算。

template<class T> bool logical_and<T>//逻辑与
template<class T> bool logical_or<T>//逻辑或
template<class T> bool logical_not<T>//逻辑非
  • 1
    点赞
  • 1
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

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

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

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值