- 函数对象是类似于函数的对象,可以是类对象或函数指针(包含函数名,因为函数名被用作指针)。
谓词
- 返回值类型为bool的普通函数或仿函数叫谓词。
- 如果普通函数有一个参数,叫一元谓词,有两个参数,叫二元谓词。
一元谓词
bool greaterThan20(int val)
{
return val>20 ;
}
class MyGreaterThan20
{
public:
bool operator()(int val)
{
return val>20;
}
}
for_each(v. begin() ,v.end(),[](int val){cout<<val<<" ";}) ;
cout< <endl;
vector<int>: : iterator ret;
ret = find_if(v.begin() ,v.end(),MyGreaterThan20()) ;
if(ret != v.end() )
{
cout<<"第一个大 于20的数为:"<<*ret<<endl ;
}
二元谓词
bool myGreater(int v1,int v2)
{
return v1>v2;
class MyGreater
{
pubVfc:
bool operator() (int vl, int v2 )
{
return v1>v2 ;
}
}
sort(v.begin() ,v.end(),MyGreater() ;
for_each(v .begin() ,v.end() ,[] (int val) {cout<<val<<" ";})
cout<<endl;
内建函数对象
6个算数类函数对象,除了negate 是一 元运算,其他都是二元运算。
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>
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>
void test03( )
{
plus<int> p;
cout<<p(10,20)<<endl ;
cout<<plus<int>() (100 , 200)<<endl ;
}