The find_if function in C++ returns the value of the initial element in the specified range that satisfies the predicate condition; otherwise, it returns the last element of the range.
Syntax
template <class InputIterator, class UnaryPredicate>
InputIterator find_if (InputIterator first, InputIterator last, UnaryPredicate pred);
Parameter
It designates the initial element within the specified range.
The final value: It designates the concluding element within the specified range.
It is typically a unary operation where the output values are examined to produce a true or false result.
Return value
The function provides an iterator pointing to the initial element within the range that satisfies the predicate condition. In cases where no such element exists, the function will return the final element instead.
Example 1
#include<iostream>
#include<algorithm>
#include<vector>
using namespace std;
bool isAnOdd(int i)
{
return((i%2)==1);
}
int main()
{
std::vector<int> newvector;
newvector.push_back(20);
newvector.push_back(35);
newvector.push_back(50);
newvector.push_back(65);
std::vector<int>::iterator ti = std::find_if(newvector.begin(), newvector.end(),isAnOdd);
std::cout<<"Out of the given elements, first odd element is "<<*ti<<"\n";
return 0;
}
Output:
Out of the given elements, first odd element is 35
Example 2
#include<iostream>
#include<algorithm>
#include<vector>
bool isEven (int i)
{
return((i%2)==0);
}
int main()
{
std::vector<int> newvector {20, 35, 50, 65};
std::vector<int>::iterator ti;
ti= std::find_if(newvector.begin(),newvector.end(),isEven);
std::cout<<"Out of the given elements, first even element is "<<*ti<<"\n";
return 0;
}
Output:
Out of the given elements, first odd element is 20
Complexity
The process progresses sequentially, beginning at the initial item and moving towards the final one. Each item in the list is inspected for the 'pred' value. The search continues until a discrepancy in the 'pred' value is found.
Data races
The function accesses either all the objects within the defined range or a subset of them.
Exceptions
The function will raise an exception if any of its arguments also raises an exception.