C++ <algorithm> std::all_of

The std::all_of function template in C++ checks if a given predicate returns true for all elements in a specified range. It is part of the C++ Standard Library’s <algorithm> header and is useful for validating that all elements in a sequence meet a certain condition.


Syntax of std::all_of

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

Parameters of std::all_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 takes an element from the range as an argument and returns a value convertible to bool. This function should not modify its argument.

Return Value of std::all_of

Returns true if the predicate pred returns true for all elements in the range [first, last) or if the range is empty; otherwise, returns false.


Exceptions for std::all_of

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


Examples for all_of

Example 1: Using std::all_of to Check for Positive Numbers

In this example, we use std::all_of to determine if all elements in a vector are positive numbers.

Program

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

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

    bool all_positive = std::all_of(numbers.begin(), numbers.end(), [](int i) {
        return i > 0;
    });

    if (all_positive) {
        std::cout << "All numbers are positive." << std::endl;
    } else {
        std::cout << "Not all numbers are positive." << std::endl;
    }

    return 0;
}

Output

All numbers are positive.

Explanation

  1. We include the necessary headers: <iostream> for input/output operations, <vector> for the std::vector container, and <algorithm> for the std::all_of function.
  2. We define a vector numbers containing the integers 1 through 5.
  3. We use std::all_of with a lambda function to check if all elements in the vector are greater than 0.
  4. If all_positive is true, we print “All numbers are positive.”; otherwise, we print “Not all numbers are positive.”

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

This example demonstrates that std::all_of returns true when applied to an empty range.

Program

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

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

    bool result = std::all_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: true

Explanation

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

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

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

Program

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

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

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

    bool all_even = std::all_of(numbers.begin(), numbers.end(), is_even);

    if (all_even) {
        std::cout << "All numbers are even." << std::endl;
    } else {
        std::cout << "Not all numbers are even." << std::endl;
    }

    return 0;
}

Output

All numbers are even.

Explanation

  1. We include the necessary headers: <iostream> for input/output operations, <list> for the std::list container, and <algorithm> for the std::all_of function.
  2. We define a custom predicate function is_even that returns true if a number is even and false otherwise.
  3. We initialize a list of integers, numbers, containing only even numbers.
  4. We use std::all_of with the custom predicate is_even to check if all elements in the list are even.
  5. If all_even is true, we print “All numbers are even.”; otherwise, we print “Not all numbers are even.”

Examples for Exceptions Thrown by std::all_of

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>

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

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

    try {
        bool result = std::all_of(numbers.begin(), numbers.end(), faulty_predicate);
        std::cout << "All elements are valid and 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 exception if a negative number is encountered.
  2. A vector numbers is initialized, which includes a negative value.
  3. The std::all_of function applies the predicate to each element of the vector.
  4. When the predicate encounters the negative number, it throws an exception.
  5. The exception is caught in the try-catch block, and an error message is printed to the console.