This tutorial will discuss about a unique way to check if all elements in array are false in C++.
To check if all the elements in array are false, we will use the std::none_of()
function from STL. It accepts the start, and end of a range, and a callback function (predicate) as arguments. Then it applies the given callback function on all the elements of array, and returns true, if it returns false for all the elements of a sequence.
So, to check if all elements of an array are false, pass the start, and end pointers of array in the std::none_of()
function. Also, pass a lambda function, that accepts an element as argument, and returns true if the given element evaluates to true.
Let’s see the complete example,
#include <iostream> #include <algorithm> int main() { bool arr[] = { false, false, false, false, false }; // Get the length of array size_t len = sizeof(arr)/sizeof(arr[0]); // Check if none of the element in array is true bool result = std::none_of( arr, arr + len, [](const bool& elem){ return elem; }); if (result) { std::cout << "Yes, all elements in the array are false." << std::endl; } else { std::cout << "No, all elements in the array are not false." << std::endl; } return 0; }
Output :
Frequently Asked:
Yes, all elements in the array are false.
Summary
Today we learned about several ways to check if all elements in array are false in C++. Thanks.
Leave a Reply
You must be logged in to post a comment.