Algorithm Find If Function - C++ Programming Tutorial
C++ Course / STL Algorithm / Algorithm Find If Function

Algorithm Find If Function

BLUF: Mastering Algorithm Find If Function is a critical step in becoming a proficient C++ developer. This lesson provides a deep dive into the syntax, performance considerations, and real-world applications of this concept.
Key Performance Insight: Algorithm Find If Function

C++ is renowned for its efficiency. Learn how Algorithm Find If Function enables low-level control and high-performance computing in the tutorial below.

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

Example

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

Example

#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:

Output

Out of the given elements, first odd element is 35

Example 2

Example

#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:

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.

Input Required

This code uses input(). Please provide values below:

Logic Practice
Install Logic Practice
Add to home screen for a faster app-like experience