This tutorial will discuss about a unique way to check if all elements in array are true in C++.
To check if all elements of array are true, we are going to use the STL algorithm std::all_of()
.
Inside STL algorithm std::all_of()
we will pass 3 arguments,
- Pointer pointing to the start of array.
- Pointer pointing to the end of array
- A Lambda function, which accepts an element as an argument and returns true if the given element is true.
The std::all_of()
function will apply the given Lambda function on all the elements of the array. If for all the elements the lambda function returns true, then the std::all_of()
function will return true.
If there is a single element that is not true in the array, then the std::all_of()
function returns false.
Let’s see the complete example,
#include <iostream> #include <algorithm> int main() { bool arr[] = { true, true, true, true, true }; // Get the size of array size_t len = sizeof(arr)/sizeof(arr[0]); // Check if all elements of array arr are true bool result = std::all_of(arr, arr + len, [](bool elem){ return elem; }); if (result) { std::cout << "Yes, all elements of array are true." << std::endl; } else { std::cout << "No, all elements of array are not true." << std::endl; } return 0; }
Output :
Frequently Asked:
- Find maximum value and its index in an Array in C++
- Declare an Array in C++
- Sort an Array in Descending Order in C++
- Check if All elements in Array are true in C++
Yes, all elements of array are true.
Summary
Today we learned about several ways to check if all elements in array are true in C++. Thanks.