C++ STL-函数对象

函数对象

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

特点:

  1. 可以有参数,可以有返回值
  2. 函数对象可以有自己的状态
  3. 函数对象可以作为参数进行传递
class MyPrint{
public:
	MyPrint(){
		this->count = 0;
	}
	void operator()(string test){  //重载调用运算符
		cout<<test<<endl;
		this->count++;
	}
	
	int count;   //内部自己状态
};

void test(){
	MyPrint myPrint;
	myPrint("hello world");
	myPrint("hello world");
	myPrint("hello world");
	cout<<"调用次数:"<<myPrint.count<<endl;
}

谓词

返回bool类型的仿函数叫做谓词,接受一个参数叫一元谓词,接受两个参数叫二元谓词。

//一元谓词
class GreaterFive{
public:
	bool operator()(int val){
		return val>5;
	}
}

void test(){
	vector<int> v;
	for(int i=0;i<10;i++){
		v.push_back(i);
	}
	//查找容器中是否有大于5的数字
	vector<int>::iterator it = find_if(v.begin(),v.end(),GreaterFive());
	if(it==v.end()){
		cout<<"没有找到"<<endl;
	}
	else{
		cout<<"找到了,这个数为"<<*it<<endl;
	}
}

STL内建仿函数

引入头文件 #include <functional>

算术仿函数

  • template<class T> T plus<T> //加
  • template<class T> T minus<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> 取反
//一元仿函数 取反
void test(){
	negate<int>n;
	cout<<n(50)<<endl;
}

//二元仿函数  加法
void test(){
	plus<int>n;
	cout<<n(50,20)<<endl;
}

关系仿函数

  • template<class T> T bool equal_to<T>
  • template<class T> T bool not_equal_to<T>
  • template<class T> T bool greater<T>
  • template<class T> T bool greater_equal<T>
  • template<class T> T bool less<T>
  • template<class T> T bool less_equal<T>

逻辑仿函数

  • template<class T> T bool logical_and<T>
  • template<class T> T bool logical_or<T>
  • template<class T> T bool logical_not<T>
  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

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

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

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值