This tutorial will discuss about a unique way to check if any element is negative in C++ array.
To check an array has any negative value, 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 negative value, we can use the std::any_of()
function. i.e.
Frequently Asked:
int arr[] = {5, 7, -11, 3, 9}; // Check if there is any negative number in the array bool result = std::any_of( std::begin(arr), std::end(arr), [](const int& elem) { return elem < 0; });
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 is negative.
The any_of()
function will return true, if there is any negative number in the array.
Let’s see the complete example,
#include <iostream> #include <algorithm> int main() { // An array of integers int arr[] = {5, 7, -11, 3, 9}; // Check if there is any negative number in the array bool result = std::any_of( std::begin(arr), std::end(arr), [](const int& elem) { return elem < 0; }); if (result) { std::cout << "Yes, Array has at least one negative number" << std::endl; } else { std::cout << "No, Array does not have any negative number" << std::endl; } return 0; }
Output :
Best Resources to Learn C++:
Yes, Array has at least one negative number
Summary
Today we learned about several ways to check if any element is negative in C++ array. Thanks.