find_if |
Locate an item that satisfies a predicate in a range.
Return an input iterator
positioned at the first element in the range [ first ,
last ) that causes pred to
return true . If no such element exists, return last
.
#include <algorithm>
template< class InputIterator, class Predicate >
InputIterator find_if
(
InputIterator first,
InputIterator last,
Predicate pred
);
Time complexity is linear, as a
maximum of ( last - first
) comparisons are performed. Space complexity is constant.
#include <iostream>
#include <algorithm>
int numbers[ 6 ] = { 2, 4, 8, 15, 32, 64 };
bool
odd( int a_ )
{
return a_ % 2;
}
void
main()
{
int* location = find_if( numbers, numbers + 6, odd );
if ( location != numbers + 6 )
cout
<< "Value "
<< *location
<< " at offset "
<< ( location - numbers )
<< " is odd"
<< "\n";
}
Value 15 at offset 3 is odd
#include <iostream>
#include <algorithm>
#include <vector>
bool
div_3( int a_ )
{
return a_ % 3 ? 0 : 1;
}
void
main()
{
vector< int > v ( 10 );
for ( size_t i = 0; i < v.size(); ++i )
v[ i ] =( i + 1 ) *( i + 1 );
vector< int > ::iterator iter;
iter = find_if( v.begin(), v.end(), div_3 );
if ( iter != v.end() )
cout
<< "Value "
<< *iter
<< " at offset "
<< ( iter - v.begin() )
<< " is divisible by 3"
<< "\n";
}
Value 9 at offset 2 is divisible by 3
Copyright©1994-2026 Recursion Software LLC
All Rights Reserved - For use by licensed users only.