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
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
#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:
There are elements which exist in the table of 2.
Example 2
#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:
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.