C++ Standard Library C++ STL Library

C++ <algorithm> - any_of() Function



The C++ algorithm::any_of function returns true if pred returns true for any element in the range [first,last), else returns false. The function returns false for empty range.

Syntax

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

Parameters

first Specify initial position of the input iterator. The range used is [first,last).
last Specify final position of the input iterator. The range used is [first,last).
pred Specify an unary function that accepts an element in the range as argument, and returns a value convertible to bool. The function returns true if the element satisfy the given condition.

Return Value

Returns true if pred returns true for any element in the range, else returns false. Returns false for empty range.

Time Complexity

Up to Linear i.e, Θ(n).

Example:

In the example below, the algorithm::any_of function is used to check whether any element of a given sequence satisfy the specified condition or not.

#include <iostream>
#include <algorithm>
#include <vector>
using namespace std;

bool isNegative (int i) {
  return (i < 0) ;
}

int main (){
  int arr[] = {10, 15, 12, -15, 14, -12};
  vector<int> vec = {10, 15, 12, 15, 14, 12};

  //check for negative element in the array
  bool b1 = any_of(arr, arr+6, isNegative);

  //check for negative element in the vector
  bool b2 = any_of(vec.begin(), vec.end(), isNegative);

  //print result for array
  if(b1) {
    cout<<"Array contains negative elements.\n";
  }
  else {
    cout<<"Array does not contain negative element.\n";
  }

  //print result for vector
  if(b2) {
    cout<<"Vector contains negative elements.\n";
  }
  else {
    cout<<"Vector does not contain negative element.\n";
  }

  return 0;
}

The output of the above code will be:

Array contains negative elements.
Vector does not contain negative element.

❮ C++ <algorithm> Library