C++ <algorithm> std::any_of

The std::any_of function template in C++ checks if any element in a given range satisfies a specified condition. It is part of the C++ Standard Library’s <algorithm> header and is used to determine if at least one element in a sequence meets a particular criterion.


Syntax of std::any_of

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

Parameters of std::any_of

ParameterDescription
firstAn input iterator to the initial position in a sequence.
lastAn input iterator to the final position in a sequence (one past the last element).
predA unary function that accepts an element in the range as an argument and returns a value convertible to bool. The value returned indicates whether the element satisfies the condition checked by this function. The function shall not modify its argument.

Return Value of std::any_of

Returns true if the predicate pred returns true for any of the elements in the range [first, last); otherwise, returns false. If the range is empty, the function returns false.


Exceptions for std::any_of

Throws an exception if either pred or an operation on an iterator throws an exception. Note that invalid parameters cause undefined behavior.


Examples for any_of

Example 1: Using std::any_of to Check for Negative Numbers

In this example, we use std::any_of to determine if any elements in a vector are negative numbers.

Program

</>
Copy
#include <iostream>
#include <vector>
#include <algorithm> // For std::any_of

int main() {
    std::vector<int> numbers = {1, 2, -3, 4, 5};

    bool has_negative = std::any_of(numbers.begin(), numbers.end(), [](int i) {
        return i < 0;
    });

    if (has_negative) {
        std::cout << "There are negative elements in the range." << std::endl;
    } else {
        std::cout << "All elements are non-negative." << std::endl;
    }

    return 0;
}

Output

There are negative elements in the range.

Explanation

  1. We include the necessary headers: <iostream> for input/output operations, <vector> for the std::vector container, and <algorithm> for the std::any_of function.
  2. We define a vector numbers containing the integers 1, 2, -3, 4, and 5.
  3. We use std::any_of with a lambda function to check if any elements in the vector are less than 0.
  4. If has_negative is true, we print “There are negative elements in the range.”; otherwise, we print “All elements are non-negative.”

Example 2: Using std::any_of with an Empty Range

This example demonstrates that std::any_of returns false when applied to an empty range.

Program

</>
Copy
#include <iostream>
#include <vector>
#include <algorithm> // For std::any_of

int main() {
    std::vector<int> empty_vector;

    bool result = std::any_of(empty_vector.begin(), empty_vector.end(), [](int i) {
        return i < 0;
    });

    std::cout << "Result for empty vector: " << std::boolalpha << result << std::endl;

    return 0;
}

Output

Result for empty vector: false

Explanation

  1. We include the necessary headers: <iostream> for input/output operations, <vector> for the std::vector container, and <algorithm> for the std::any_of function.
  2. We define an empty vector empty_vector.
  3. We use std::any_of with a lambda function to check if any elements in the empty vector are less than 0. Since the range is empty, std::any_of returns false.
  4. We print the result, which is false, indicating that no elements satisfy the condition in an empty range.

Example 3: Using std::any_of with a Custom Predicate

In this example, we define a custom predicate function to check if any elements in a list are odd numbers.

Program

</>
Copy
#include <iostream>
#include <list>
#include <algorithm> // For std::any_of

bool is_odd(int n) {
    return n % 2 != 0;
}

int main() {
    std::list<int> numbers = {2, 4, 6, 8, 10};

    bool has_odd = std::any_of(numbers.begin(), numbers.end(), is_odd);

    if (has_odd) {
        std::cout << "There are odd numbers in the list." << std::endl;
    } else {
        std::cout << "All numbers are even." << std::endl;
    }

    return 0;
}

Output

All numbers are even.

Explanation

  1. The program includes the necessary headers: <iostream> for input/output operations, <list> for the std::list container, and <algorithm> for the std::any_of function.
  2. A custom predicate function is_odd is defined, which returns true if a number is odd and false otherwise.
  3. A list numbers is initialized with even numbers: 2, 4, 6, 8, and 10.
  4. The std::any_of function is used with the custom predicate to check if any number in the list is odd.
  5. Since all numbers are even, has_odd is false, and the program outputs “All numbers are even.”

Examples to Handle Exceptions thrown by algorithm any_of Function

Example 1: Predicate Throws an Exception

This example demonstrates a case where the predicate function throws an exception during execution.

Program

</>
Copy
#include <iostream>
#include <vector>
#include <algorithm>
#include <stdexcept>

bool faulty_predicate(int n) {
    if (n < 0) {
        throw std::runtime_error("Negative number encountered.");
    }
    return n % 2 == 0;
}

int main() {
    std::vector numbers = {-2, 4, -6, 8, 10};

    try {
        bool result = std::any_of(numbers.begin(), numbers.end(), faulty_predicate);
        std::cout << "At least one element is even: " << std::boolalpha << result << std::endl;
    } catch (const std::runtime_error& e) {
        std::cout << "Exception caught: " << e.what() << std::endl;
    }

    return 0;
}

Output

Exception caught: Negative number encountered.

Explanation

  1. The program defines a predicate function faulty_predicate that throws a std::runtime_error if a negative number is encountered.
  2. A vector numbers is initialized, including a negative number.
  3. The std::any_of function applies the predicate to each element of the vector. When it encounters the negative number, the predicate throws an exception.
  4. The exception is caught in the try-catch block, and an error message is printed.

Example 2: Iterator Throws an Exception

This example demonstrates a case where a custom iterator throws an exception during iteration.

Program

</>
Copy
#include <iostream>
#include <vector>
#include <algorithm>
#include <stdexcept>

class FaultyIterator {
public:
    using iterator_category = std::input_iterator_tag;
    using value_type = int;
    using difference_type = std::ptrdiff_t;
    using pointer = const int*;
    using reference = const int&;

    FaultyIterator(const int* ptr, bool fail_after = false)
        : ptr(ptr), fail_after(fail_after), count(0) {}

    reference operator*() const {
        if (fail_after && count >= 0) {
            throw std::runtime_error("Iterator error.");
        }
        return *ptr;
    }

    FaultyIterator& operator++() {
        ++ptr;
        ++count;
        return *this;
    }

    bool operator!=(const FaultyIterator& other) const {
        return ptr != other.ptr;
    }

    bool operator==(const FaultyIterator& other) const {
        return ptr == other.ptr;
    }

private:
    const int* ptr;
    bool fail_after;
    int count;
};

int main() {
    int arr[] = {1, 2, 3};

    try {
        bool result = std::any_of(
            FaultyIterator(arr, true), 
            FaultyIterator(arr + 3), 
            [](int n) { return n > 0; });
        std::cout << "At least one positive element: " << std::boolalpha << result << std::endl;
    } catch (const std::runtime_error& e) {
        std::cout << "Exception caught: " << e.what() << std::endl;
    }

    return 0;
}

Output

Exception caught: Iterator error.

Explanation

  1. The program defines a custom iterator FaultyIterator that throws a std::runtime_error after accessing two elements.
  2. An array arr is initialized with three elements.
  3. The std::any_of function applies a lambda predicate to the elements. The iterator throws an exception during iteration.
  4. The exception is caught in the try-catch block, and an error message is printed.