-2

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;
        }
    }
  • 3
    The only way to avoid iterating over the array is if you have extra information about the position of the elements in the array, for example if it is sorted. – François Andrieux Oct 20 '20 at 16:56
  • 3
    Can you show us what you've tried? Without seeing your attempt, it's hard to say what'd be more or less "efficient." Also, is there a reason you're trying to make this more "efficient?" Is it too slow as is and that's causing issues? – scohe001 Oct 20 '20 at 16:56
  • 1
    Without any other information of the given array, the efficiency cannot be improved over for-loop over it. – Wander3r Oct 20 '20 at 17:00
  • Ok, sorry for lack of information. I updated this question. – Michał Dobranowski Oct 21 '20 at 15:03

1 Answers1

3

If you don't want to use a for loop, use a standard algorithm instead, for example:

std::find_if()

#include <algorithm>

int arr[] = ...;
int n = ...;

auto end = arr + n;
if (std::find_if(arr, end, [](int i){ return i > 0; }) != end)
{
    ...
}

std::any_of()

#include <algorithm>

int arr[] = ...;
int n = ...;

if (std::any_of(arr, arr + n, [](int i){ return i > 0; }))
{
    ...
}

std::none_of()

#include <algorithm>

int arr[] = ...;
int n = ...;

if (std::none_of(arr, arr + n, [](int i){ return i == 0; }))
{
    ...
}
Remy Lebeau
  • 555,201
  • 31
  • 458
  • 770