How to use the find_if() function in C++

The find_if() function is available in the <algorithm.h> header file in C++. This function helps search for an element in a list based on a condition. The condition needs to be true for the element to be searched.

Parameters

The find_if() function accepts the following parameters:

  • first: This is an iterator that points to the first index of the array or vector where we want to perform the search operation.

  • last: This is an iterator that points to the last index of the array or vector to where we want to perform the search operation.

  • condition: This is a unary function that accepts one element and returns a boolean value indicating whether the condition is satisfied or not.

Return

The find_if() function returns an iterator pointing to the first element satisfying the condition. If no such element is found, it returns an iterator pointing to the last element of the vector.

Code

Let’s have a look at the code:

#include <iostream>
#include <algorithm>
#include <vector>
using namespace std;
bool IsOdd (int i) {
return (i % 2) == 1;
}
int main () {
vector<int> vec = {10, 25, 5, 30, 3};
auto it = find_if(vec.begin(), vec.end(), IsOdd);
cout << "The first odd value is " << *it;
return 0;
}

Explanation:

  • From lines 1 to 3, we import the required header files.
  • In line 6, we create a unary function that returns a boolean value indicating whether the number is oddreturn true or notreturn false.
  • In line 11, we create a vector of integers.
  • In line 12, we call the find_if() function and pass all the required parameters.
  • In line 14, we print the first element that satisfies the given conditionthe number is odd.

Free Resources