So, I have an array in C++ of length n
and I want to know if it contains at least one positive number. I know for sure that the array contains only non-negative numbers.
I know how to do that but I wonder if there's a more efficient or prettier method than for-loop over the array.
I have something like this:
bool is_empty = true;
for(int i = 0; i < n; i++) {
if(arr[i] > 0) {
is_empty = false;
break;
}
}
If you don't want to use a for
loop, use a standard algorithm instead, for example:
#include <algorithm>
int arr[] = ...;
int n = ...;
auto end = arr + n;
if (std::find_if(arr, end, [](int i){ return i > 0; }) != end)
{
...
}
#include <algorithm>
int arr[] = ...;
int n = ...;
if (std::any_of(arr, arr + n, [](int i){ return i > 0; }))
{
...
}
#include <algorithm>
int arr[] = ...;
int n = ...;
if (std::none_of(arr, arr + n, [](int i){ return i == 0; }))
{
...
}