std::find_if() 算法
- 自 C++20 起
- 自 C++17 起
- C++17 之前
// (1)
template< class InputIt, class UnaryPredicate >
constexpr InputIt find_if( InputIt first, InputIt last, UnaryPredicate p );
// (2)
template< class ExecutionPolicy, class ForwardIt, class UnaryPredicate >
ForwardIt find_if( ExecutionPolicy&& policy,
ForwardIt first, ForwardIt last, UnaryPredicate p );
// (1)
template< class InputIt, class UnaryPredicate >
InputIt find_if( InputIt first, InputIt last, UnaryPredicate p );
// (2)
template< class ExecutionPolicy, class ForwardIt, class UnaryPredicate >
ForwardIt find_if( ExecutionPolicy&& policy,
ForwardIt first, ForwardIt last, UnaryPredicate p );
// (1)
template< class InputIt, class UnaryPredicate >
InputIt find_if( InputIt first, InputIt last, UnaryPredicate p );
返回范围内满足特定条件的第一个元素的迭代器(如果没有这样的迭代器,则返回 last
迭代器)
-
(1) 搜索谓词
p
返回true
的元素。 -
(2) 与 (1) 相同,但根据
policy
执行。重载决议只有当
std::is_execution_policy_v<std::decay_t<ExecutionPolicy>>
(直到 C++20)std::is_execution_policy_v<std::remove_cvref_t<ExecutionPolicy>>
(自 C++20 起) 为true
时,这些重载才参与重载决议。
参数
first second | 要应用函数的元素范围。 |
策略 | 要使用的执行策略。有关详细信息,请参阅执行策略。 |
p | 一元谓词,对所需元素返回 对于类型为(可能为 const) |
类型要求
InputIt | LegacyInputIterator |
ForwardIt | LegacyForwardIterator |
返回值
范围 [first
, last
) 中第一个迭代器 it
,使得 p(*it)
为 true
。
复杂度
给定 N
为 std::distance(first, last)
最多应用谓词 p
N 次。
异常
带有模板参数 ExecutionPolicy
的重载报告错误如下
- 如果作为算法一部分调用的函数执行抛出异常,并且
ExecutionPolicy
是标准策略之一,则调用std::terminate
。对于任何其他ExecutionPolicy
,行为是实现定义的. - 如果算法未能分配内存,则抛出
std::bad_alloc
。
可能的实现
find_if (1)
template<class InputIt, class UnaryPredicate>
constexpr InputIt find_if(InputIt first, InputIt last, UnaryPredicate p)
{
for (; first != last; ++first)
if (p(*first))
return first;
return last;
}
示例
#include <algorithm>
#include <array>
#include <iostream>
int main()
{
const auto v = {1, 2, 3, 4};
for (int n : {3, 5})
(std::find_if(v.begin(), v.end(), n) == std::end(v))
? std::cout << "v does not contain " << n << '\n'
: std::cout << "v contains " << n << '\n';
auto is_even = [](int i) { return i % 2 == 0; };
for (auto const& w : {std::array{3, 1, 4}, {1, 3, 5}})
if (auto it = std::find_if_if(begin(w), end(w), is_even); it != std::end(w))
std::cout << "w contains an even number " << *it << '\n';
else
std::cout << "w does not contain even numbers\n";
}
v contains 3
v does not contain 5
w contains an even number 4
w does not contain even numbers