How to use the any_of() function in C++

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.

Parameters

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 satisfiedreturns true or notreturns false.

Return

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.

Code

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;
}

Explanation

  • From lines 1 to 3, we import the required header files.
  • In line 6, we create our unary function that will return true if the number is odd; otherwise, it will return false.
  • In line 11, we create a vector of integers.
  • In line 13, we call the any_of() function and pass the required parameters.
  • Then, in line 14, we print if any of the elements is odd. Otherwise, we print in line 16 that all the elements are even.

Free Resources