19.2谓词
概念:
- 返回boo类型的仿函数称为谓词
- 如果operator()接受一个参数,那么叫做一元谓词
- 如果operator()接受两个参数,那么叫做二元谓词
谓词一般作为其他函数的参数来使用,如find_if函数。
我们转到find_if底层实现:
// FUNCTION TEMPLATE 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);
}
目前我们的水平看这些底层代码非常吃力,但我们只要知道:
find_if(_InIt _First, const _InIt _Last, _Pr _Pred)
这里看出find_if有三个参数,前两个是迭代器,第三个是谓词。一般pred就是指谓词。
接下来是for循环,这里谓词自动传入的参数是迭代器的解引用,如果为真就退出循环。
for (; _UFirst != _ULast; ++_UFirst)
{
if (_Pred(*_UFirst))
{
break;
}
}
find_if函数最后返回了一个迭代器。
利用这些,本节示例:
#include <iostream>
#include <vector>
#include <algorithm>
using namespace std;
class GreaterFive
{
public:
bool operator()(int val)
{
return val > 5;
}
};
void test1()
{
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;
}
}
int main()
{
test1();
}