在 STL 中,find_if() 函数和 find() 函数相同,find_if() 函数也用于在指定区域内执行查找操作。不同的是,前者需要明确指定要查找的元素的值,而后者则允许自定义查找规则。
#include <algorithm>
InputIterator find_if (InputIterator first, InputIterator last, UnaryPredicate pred);
参数 | 描述 |
---|---|
first | 输入迭代器 |
last | 输入迭代器 |
pred | 自定义查找规则 |
其中,first 和 last 都为输入迭代器,其组合 [first, last) 用于指定要查找的区域;pred 用于自定义查找规则。
由于 first 和 last 都为输入迭代器,意味着该函数适用于所有的序列式容器。甚至当采用适当的谓词函数时,该函数还适用于所有的关联式容器(包括哈希容器)。
同时,该函数会返回一个输入迭代器,当查找成功时,该迭代器指向的是第一个符合查找规则的元素;反之,如果 find_if() 函数查找失败,则该迭代器的指向和 last 迭代器相同。
使用 STL find_if 函数查找集合
#include <iostream>
#include <algorithm>
#include <vector>
using namespace std;
class mycomp
{
public:
bool operator()(const int& i)
{
return ((i % 2) == 1);
}
};
int main()
{
cout << "嗨客网(www.haicoder.net)\n" << endl;
vector<int> myvector{99, 101, 200, 206, 301};
vector<int>::iterator it = find_if(myvector.begin(), myvector.end(), mycomp());
cout << "*it = " << *it;
cout << endl;
return 0;
}
我们在 Linux 下使用 g++ 进行编译,具体命令如下:
g++ find_if.cpp -std=c++11
编译后,我们直接运行生成的二进制文件 a.out
,如下图所示:
我们首先,使用了 find_if 函数,加上自定义规则在 vector 中查找了元素。
在 STL 中,find_if() 函数和 find() 函数相同,find_if() 函数也用于在指定区域内执行查找操作。不同的是,前者需要明确指定要查找的元素的值,而后者则允许自定义查找规则。