The any_of()
function in C++ helps to determine if any of the elements in an array in the specified range satisfy the condition or not. This function is available in the <algorithm.h>
header file.
The any_of()
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 this check.
last
: This is an iterator that points to the last index of the array or vector where we want to perform this check.
condition
: This is an unary function that accepts one element of the same type as elements you have in the array or vector. This unary function returns a Boolean value that indicates whether the condition is
The any_of()
function returns a Boolean value true
if any of the elements present in the array or vector in the specified range satisfy the condition; otherwise, it returns false
.
Let’s look at the code now.
#include <iostream> #include <vector> #include <algorithm> using namespace std; bool IsAnyOdd(int i){ return (i % 2 == 1); } int main() { vector<int> vec = {2,4,6,8,10,12,15,18,20}; if (any_of(vec.begin(), vec.end(), IsAnyOdd)) cout << "At least one number is odd."; else cout << "All the elements are even."; return 0; }
true
if the number is odd; otherwise, it will return false
.any_of()
function and pass the required parameters.RELATED TAGS
CONTRIBUTOR
View all Courses