This tutorial will discuss about a unique way to check if all elements in array are zero in C++.
To check if all elements of array are zero, 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 zero.
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 zero in the array, then the std::all_of()
function returns false.
Let’s see the complete example,
#include <iostream> #include <algorithm> int main() { int arr[] = { 0, 0, 0, 0, 0 }; // Get the size of array size_t len = sizeof(arr)/sizeof(arr[0]); // Check if all elements of array arr are zero bool result = std::all_of(arr, arr + len, [](bool elem){ return elem == 0; }); if (result) { std::cout << "Yes, all elements of array are zero." << std::endl; } else { std::cout << "No, all elements of array are not zero." << std::endl; } return 0; }
Output :
Frequently Asked:
- Check if Any element in Array is NULL in C++
- How to check if an Array is Sorted in C++
- Find maximum value and its index in an Array in C++
- How to return an Array from a function in C++
Yes, all elements of array are zero.
Summary
Today we learned about several ways to check if all elements in array are zero in C++. Thanks.