Friday, October 28, 2022

[FIXED] How to check if an array is filled with zeros in C++

Issue

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;
        }
    }

Solution

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; }))
{
    ...
}


Answered By - Remy Lebeau
Answer Checked By - Pedro (PHPFixing Volunteer)

No comments:

Post a Comment

Note: Only a member of this blog may post a comment.