Algorithm Any Of Function - C++ Programming Tutorial
C++ Course / STL Algorithm / Algorithm Any Of Function

Algorithm Any Of Function

BLUF: Mastering Algorithm Any Of 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 Any Of Function

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

The any_of function in C++ evaluates the 'pred' condition for each element within the range. If 'pred' returns true for at least one element, the function will return true; otherwise, it will return false.

Syntax

Example

template <class InputIteratir, class UnaryPredicate>
bool any_of (InputIterator first, InputIterator last, UnaryPredicate pred);

Parameter

It represents the initial element within the specified range.

last : It is the last element in the range.

It is a unary function that takes an argument from the specified range.

Return value

The function returns the type 'true' if the argument 'pred' evaluates to true for any element within the range; otherwise, it returns false.

Example 1

Example

#include <iostream>
#include <algorithm>
#include <array>
using namespace std;
int main()
{
	int arr[7] = {2,4,6,5,10,3,14};
	any_of(arr,arr+6, [](int k){return k%2;})?
	cout <<"There are elements which exist in the table of 2":
	cout<<"No elements in the table of 2 exists";
	return 0;
}

Output:

Output

There are elements which exist in the table of 2.

Example 2

Example

#include <iostream>
#include <algorithm>
#include <array>
int main()
{
	std::array<int, 5> arr = {2,-4,6,-9,10};
	if(std::any_of (arr.begin(), arr.end(), [](int k) { return k<0;}))
	std::cout <<"Negative elements exist in the array";
	return 0;
}

Output:

Output

Negative elements exist in the array

Complexity

The process moves sequentially, beginning from the initial item and progressing towards the final one. Each item in the collection undergoes a verification of the 'pred' value. The iteration continues until a discrepancy in the 'pred' value is identified.

Data races

Either the function retrieves all the items within the defined range or a subset of them.

Exceptions

The function will raise an exception if any of the 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