Facebook Page Twitter Page LinkedIn Page
× C++ Standard Library C++ STL Library


The C++ algorithm::find_if function is used to return an iterator to the first element in the range [first,last) for which the unary function pred returns true.

Syntax

template <class InputIterator, class UnaryPredicate>
   InputIterator find_if (InputIterator first, 
                          InputIterator last, 
                          UnaryPredicate pred);

Parameters

first Specify initial position of the input iterator. The range used is [first,last).
last Specify final position of the input iterator. The range used is [first,last).
pred Specify an unary function that accepts an element in the range as argument, and returns a value convertible to bool. The element will be considered a match if the function returns true.

Return Value

Returns an iterator pointing to the first element in the range for which pred returns true. If pred returns false for all elements in the range, the function returns last.

Time Complexity

Linear i.e, Θ(n).

Example:

In the below example, the algorithm::find_if function is used to find first negative number in the given sequence.

#include <iostream>
#include <algorithm>
#include <vector>
using namespace std;

bool isNegative (int i) {
  return (i < 0) ;
}

int main (){
  int arr[] = {10, 15, 12, -15, 14, -12};
  int * p;
  vector<int> vec = {10, 15, 12, 15, 14, 12};
  vector<int>::iterator it;

  //search for negative number in the array
  p = find_if(arr, arr+6, isNegative);

  //search for negative number in the vector
  it = find_if(vec.begin(), vec.end(), isNegative);

  //print result for array
  if(p != arr+6) {
    cout<<"Element found in the array: "<<*p<<"\n";
  }
  else {
    cout<<"Element is not found in the array.\n";
  }

  //print result for vector
  if(it != vec.end()) {
    cout<<"Element found in the vector: "<<*it<<"\n";
  }
  else {
    cout<<"Element is not found in the vector.\n";
  }

  return 0;
}

The output of the above code will be:

Element found in the array: -15
Element is not found in the vector.

❮ C++ <algorithm> Library