Check if All elements are Greater than a Number in C++

This tutorial will discuss about a unique way to check if all elements are greater than a number in C++.

To check if all the elements of an array are greater than a given number, we need to iterate over all the elements of array and check each element one by one.

For that we can use a STL Algorithm std::all_of(), which accepts three arguments,

  • The iterator pointing to the start of array.
  • The iterator pointing to the end of array.
  • A Lambda function
    • This lambda function accept one argument and returns true, if the given argument is greater than specific number, otherwise returns false.

The std::all_of() function will apply the given Lambda function on all the elements of array, and returns true only if the Lambda function returns true for all the elements of the array. The syntax is as follows,

int arr[] = {18, 19, 26, 11, 22, 25, 12, 14};
int number = 10;

// Check if all numbers are greater than a specific number
bool result = std::all_of(
                std::begin(arr),
                std::end(arr),
                [&](const int& elem) {
                    return elem > number;
                });

Here, the std::all_of() function function will return true, if all the numbers in the array are greater than a specific number i.e. number 10.

Let’s see the complete example,

#include <iostream>
#include <algorithm>

int main()
{
    int arr[] = {18, 19, 26, 11, 22, 25, 12, 14};
    int number = 10;

    // Check if all numbers are greater than a specific number
    bool result = std::all_of(
                    std::begin(arr),
                    std::end(arr),
                    [&](const int& elem) {
                        return elem > number;
                    });

    if(result)
    {
        std::cout << "Yes, all elements in the array are greater than a specifc number \n";
    }
    else
    {
        std::cout << "No, all elements in the array are not greater than a speciifc number" << std::endl;
    }
    return 0;
}

Output :

Yes, all elements in the array are greater than a specifc number

Summary

Today we learned about a way to check if all elements are greater than a number 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