I have forgotten
my Password

Or login with:

  • Facebookhttp://facebook.com/
  • Googlehttps://www.google.com/accounts/o8/id
  • Yahoohttps://me.yahoo.com


Searches for the first element that matches a criterion


The find_if() algorithm is defined in the standard header <algorithm> and in the nonstandard backward-compatibility header <algo.h>.


#include <algorithm>
template < class InputIterator, class Predicate>
   InputIterator find_if(
      InputIterator first, 
      InputIterator last, 
      Predicate pred

Parameter Description
first An input iterator addressing the position of the first element in the range to be searched
last An input iterator addressing the position one past the final element in the range to be searched
pred User-defined predicate function object that defines the condition to be satisfied by the element being searched for. A predicate takes single argument and returns true or false


The find_if() algorithm searches the range [first, last) for a value that satisfies the unary predicate pred.

Return Value

Returns an iterator pointing to the first value from the given range that satisfies pred, or last if no such value is found.


Complexity is linear, at most, performs as many applications of pred as the number of elements in the range [first,last).

Example - find_if algorithm
This program determines if an integer is divisible by 3. Returns true if n is divisible by 3, and otherwise false.
#include <iostream>
#include <algorithm>
#include <vector>
using namespace std;
bool isDivisibleByThree
  int n //in
  return (n%3 == 0);
int main()
  int a[] = {1, 2, 4, 5, 7, 12, 9, 8, 3, 6};
  vector<int> v(a, a+10);
  cout <<"\nHere are the contents of v:\n";
  for (vector<int>::size_type i=0; i<v.size(); i++)
    cout <<v.at(i)<<" ";
  vector<int>::iterator p;
  p = find_if(v.begin(), v.end(), isDivisibleByThree);
  if (p == v.end())
    cout <<"\nThere are no values divisible by 3.\n";
    cout <<"\nThe first value in the sequence divisible by 3 is " 
         <<*p<<",\nwhich was found at location "
  return 0;

Here are the contents of v:
1 2 4 5 7 12 9 8 3 6

The first value in the sequence divisible by 3 is 12,
which was found at location 6.

See Also