std::
find_if
函数模板 <algorithm>
template <class InputIterator, class UnaryPredicate>
InputIterator find_if (InputIterator first, InputIterator last, UnaryPredicate pred); |
在范围内查找值
返回一个指向[first,last]范围内pred返回true的第一个元素的迭代器。
这个函数模板的行为相当于:
template<class InputIterator, class UnaryPredicate>
InputIterator find_if (InputIterator first, InputIterator last, UnaryPredicate pred)
{
while (first!=last) {
if (pred(*first)) return first;
++first;
}
return last;
} |
☲ 参数
-
first, last
-
指向序列初始和最终位置的输入迭代器。使用的范围是[first,last],
它包含first和last之间的所有元素,包括first指向的元素,但不包括last指向的元素。
-
pred
-
接受范围内元素作为参数并返回可转换为bool的值的一元函数。
返回的值表明该元素在该函数当前环境中是否匹配。
函数不应修改其参数。
它可以是函数指针,也可以是函数对象。
☉ 返回值
指向pred不返回false的范围内第一个元素的迭代器。
如果pred对所有元素都为false,函数返回last。
☣ 示例
// find_if example
#include <iostream> // std::cout
#include <algorithm> // std::find_if
#include <vector> // std::vector
bool IsOdd (int i) {
return ((i%2)==1);
}
int main () {
std::vector<int> myvector;
myvector.push_back(10);
myvector.push_back(25);
myvector.push_back(40);
myvector.push_back(55);
std::vector<int>::iterator it = std::find_if (myvector.begin(), myvector.end(), IsOdd);
std::cout << "The first odd value is " << *it << '\n';
return 0;
} |
输出:
The first odd value is 25
✥ 复杂度
在first 和last之间的distance达到线性:对每个元素调用pred,直到找到匹配。
⇄ 数据竞争
[first,last)范围内的部分(或全部)对象被访问(最多一次)。
☂ 异常安全性
如果迭代器上的pred或操作抛出,则抛出。
注意,无效的参数会导致未定义的行为。
🍄 另请参阅
find |
在范围内查找值(函数模板) |
for_each |
将函数应用于范围(函数模板) |