Check if Any value in Array is greater than a Value in C++

This tutorial will discuss about a unique way to check if any value in array is greater than a value in C++.

To check an array has any value that is greater than a specified number, we will use the std::any_of() function from STL Algorithms.

The std::any_of() function accepts three arguments,

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

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

So, to check if an array contains a value greater than a specified number, we can use the std::any_of() function. For example, to check if array has any value greater than 90, we will use the following code,

// Get the size of array
size_t len = sizeof(arr) / sizeof(arr[0]);

// Checks if any element in Array is greater than 90
bool result =  std::any_of(arr,
                            arr + len,
                            [](int elem) {
                                return elem > 90;
                            }) ;

We passed three arguments in the std::any_of() function,

  • Iterator pointing to the start of array i.e. iterator returned by std::begin(arr).
  • Iterator pointing to the end of array i.e. iterator returned by std::end(arr).
  • A Lambda function which accepts an integer as an argument, and returns true if the given number greater then 90. Otherwise it will return false.

The any_of() function will return true, if any number in the array is greater than 90.

Let’s see the complete example,

#include <iostream>
#include <algorithm>

int main()
{
    int arr[] = {46, 76, 18, 92, 23, 67, 98};

    // Get the size of array
    size_t len = sizeof(arr) / sizeof(arr[0]);

    // Checks if any element in Array is greater than 90
    bool result =  std::any_of(arr,
                               arr + len,
                               [](int elem) {
                                    return elem > 90;
                               }) ;

    if(result)
    {
        std::cout << "Yes, at least one element of Array arr is greater than a given number\n";
    }
    else
    {
        std::cout << "No, none of the Array element is greater than a given number\n";
    }

    return 0;
}

Output :

Yes, at least one element of Array arr is greater than a given number

Summary

Today we learned about several ways to check if any value in array is greater than a value 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