Check if all elements of Array matches a Condition in C++

This tutorial will discuss about a unique way to check if all elements of an array matches a condition in C++.

To check if all elements of an array matches a condition, we will use the std::all_of() function from STL Algorithms. An Intro about std::all_of() function:

It accepts three arguments

  • Iterator/Pointer pointing to the start of a sequence.
  • Iterator/Pointer pointing to the end of a sequence.
  • A function which accepts a value of same type as the type of sequence, and returns a boolean value.

The std::all_of() function will apply the given function on all the elements of the sequence and it returns true if the callback function returns true for all the elements of the sequence.

To check if all elements of an array matches a condition, we will pass the iterator pointing to the start & end of array as first two arguments in the all_of() function. As the 3rd argument we will pass a condition, which can be a global function or a Lambda function. But this function should accept an element as an argument and must return a boolean value. The all_of() function will apply this condition on all the elements of the array and if the condition satisfies for all the elements (Lambda function returns true for all the elements), then the all_of() function will return true. It means that the all elements of array match is then given condition.

Like in the below example, we will check if all the elements of array are even or not.

Let’s see the complete example,

#include <iostream>
#include <algorithm>

int main()
{
    int arr[] = { 32, 44, 88, 68, 50, 36 };

    // Check if all elements matches a condition i.e.
    // if all elements in array are even
    bool result = std::all_of(
                        std::begin(arr),
                        std::end(arr),
                        [](const int& elem){
                            return elem % 2 == 0;
                        });

    if (result)
    {
        std::cout << "Yes, all elements in the array matches a condition." << std::endl;
    }
    else
    {
        std::cout << "No, all elements in the array do not matches a condition." << std::endl;
    }

    return 0;
}

Output :

Yes, all elements in the array matches a condition.

Summary

Today we learned about several ways to check if all elements of an array matches a condition in C++. Thanks.

Leave a Comment

Your email address will not be published. Required fields are marked *

This site uses Akismet to reduce spam. Learn how your comment data is processed.

Scroll to Top