一元函数对象和一元谓词

谓词:

一元函数对象:函数参数1个;

二元函数对象:函数参数2个;

一元谓词 函数参数1个,函数返回值是bool类型,可以作为一个判断式

谓词可以使一个仿函数,也可以是一个回调函数。

二元谓词 函数参数2个,函数返回值是bool类型

 

一元谓词函数举例如下:

1,判断给出的string对象的长度是否小于6

bool GT6(const string &s)

{

return s.size() >= 6;

}

2,判断给出的int是否在38之间

bool Compare( int i )

{

return ( i >= 3 && i <= 8 );

}

#include <iostream>  
#include<string>  
#include <vector>  
#include <list>  
#include <set>  
#include <map>  
#include <algorithm>  
#include <functional>
using namespace std;

class IsEven
{
public:
	IsEven()
	{
		n = 0;
	}
	bool operator()(int num)
	{
		if (num%2==0)
		{
			n++;
			return true;
		}
		return false;
	}
	int returnN()
	{
		return n;
	}
protected:
private:
	int n;//记录偶数的个数
};

void display()
{
	vector<int> v;
	v.push_back(1);
	v.push_back(2);
	v.push_back(3);
	v.push_back(4);
	v.push_back(5);
	v.push_back(6);
	v.push_back(7);
	v.push_back(10);

	IsEven is;
	//统计vector中的偶数个数
	is = for_each(v.begin(),v.end(),is);
	cout<<is.returnN()<<endl;
	
	//查找vector第一个偶数的位置
	vector<int>::iterator it;
	/*
	template<class _InIt,
	class _Pr> inline
	_InIt find_if(_InIt _First, _InIt _Last, _Pr _Pred)
	{	// find first satisfying _Pred
	_DEBUG_RANGE(_First, _Last);
	_DEBUG_POINTER(_Pred);
	return (_Rechecked(_First,
	_Find_if(_Unchecked(_First), _Unchecked(_Last), _Pred)));
	}
	*/
	//find_if 返回一个迭代器
	it = find_if(v.begin(),v.end(),is);
	if (it!=v.end())
	{
		cout<< *it<<endl;
	}
	else
	{
		cout<<"没有"<<endl;
	}
}

int main()
{
	display();
	system("pause");
	return 0;
}



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

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

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

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值