any_of function is used to test condition on the elements in a range[first,last), it will return true if the test condition is true for any of the element in the range, else it will return false or if the range is empty. To use this function we have to include "algorithm" header file in our program.
Function Prototype
bool any_of (InputIterator first, InputIterator last, UnaryPredicate pred);
About the parameters
first
It is the initial position of the range which is included in the range.
last
It is the last position in the range, which is not included in the range.
pred
It is a unary function which return value which is convertible to bool. This function is used to test condition on the element in the range.
Sample program using any_of
#include <iostream>
#include <algorithm>
using namespace std;
int main()
{
int arr_one[] = {2,4,6,8,10};
int arr_two[] = {2,3,6,8,10};
cout << "\nElements inside the range : ";
for (int x:arr_one) {
cout << x << " ";
}
cout << endl;
if ( any_of(arr_one,arr_one+5,[](int i){return (i%2);})) {
cout << "Element(s) in the range are odd.\n";
} else {
cout << "Element(s) in the range are not odd.\n";
}
cout << "\nElements inside the range : ";
for (int x:arr_two) {
cout << x << " ";
}
cout << endl;
if ( any_of(arr_two,arr_two+5,[](int i){return (i%2);})) {
cout << "Element(s) in the range are odd.\n";
} else {
cout << "Element(s) in the range are not odd.\n";
}
return 0;
}
Output of the program
Elements inside the range : 2 4 6 8 10
Element(s) in the range are not odd.
Elements inside the range : 2 3 6 8 10
Element(s) in the range are odd.
Complexity is of any_of is up to linear in between the range, the pred is called until a match is found
0 Comment(s)