谓词:
一元函数对象:函数参数1个;
二元函数对象:函数参数2个;
一元谓词 函数参数1个,函数返回值是bool类型,可以作为一个判断式
谓词可以使一个仿函数,也可以是一个回调函数。
二元谓词 函数参数2个,函数返回值是bool类型
一元谓词函数举例如下:
1,判断给出的string对象的长度是否小于6
bool GT6(const string &s)
{
return s.size() >= 6;
}
2,判断给出的int是否在3到8之间
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;
}