一元函数对象:函数参数1个
二元函数对象:函数参数2个
一元谓词 函数参数1个,函数返回值是bool类型,可以作为一个判断式,谓词可以是一个仿函数,也可以是一个回调函数。
二元谓词 函数参数2个,函数返回值是bool类型
之所以给返回布尔类型的函数对象专门命名,是因为谓词是用来为算法判断服务的。
一元谓词
template <typename T>
class IsDiv
{
public:
IsDiv(const T divisor)
{
this->divisor = divisor;
}
bool operator()(T &t)
{
return (t%divisor) == 0;
}
private:
T divisor;
};
void Fun3()
{
vector<int> v1;
for (int i = 10; i < 30; i++)
{
v1.push_back(i);
}
int divisor = 4;
IsDiv<int> isDiv(divisor);
//使用谓词来做函数参数 返回一个迭代器
vector<int>::iterator it = find_if(v1.begin(), v1.end(), IsDiv<int>(divisor));
if (it == v1.end())
{
cout << "不能被5整除" << endl;
}
else
{
cout <<"第一个能被"<< divisor<<"整除的数:"<< *it << endl;
}
}
find_if使用谓词来做函数参数 返回一个迭代器的地址
template<class _InIt,
class _Pr>
_NODISCARD inline _InIt find_if(_InIt _First, const _InIt _Last, _Pr _Pred)
{ // find first satisfying _Pred
_Adl_verify_range(_First, _Last);
auto _UFirst = _Get_unwrapped(_First);
const auto _ULast = _Get_unwrapped(_Last);
for (; _UFirst != _ULast; ++_UFirst)
{
if (_Pred(*_UFirst))
{
break;
}
}
_Seek_wrapped(_First, _UFirst);
return (_First);
}
二元函数对象
template <typename T>
class SumAdd
{
public:
T operator()(T &t1, T &t2)
{
return t1 + t2;
}
};
void Fun4()
{
vector<int> v1, v2, v3;
v1.push_back(1);
v1.push_back(2);
v1.push_back(3);
v2.push_back(4);
v2.push_back(5);
v2.push_back(6);
v3.resize(5);
transform(v1.begin(), v1.end(), v2.begin(), v3.begin(), SumAdd<int>());
for (vector<int>::iterator it = v3.begin();it <v3.end();it++)
{
cout << *it << " ";
}
}
二元谓词
bool MyCompare(const int &a,const int &b)
{
return a < b;
}
void Fun5()
{
vector<int> v1;
for (int i = 0; i < 10; i++)
{
v1.push_back(rand() % 100);
}
for_each(v1.begin(), v1.end(), PrintElement1<int>);
cout << "排序之后" << endl;
sort(v1.begin(), v1.end(), MyCompare);
for_each(v1.begin(), v1.end(), PrintElement2);
}