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.
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.
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.
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;}
find_if()
function and pass all the required parameters.