PHPFixing
  • Privacy Policy
  • TOS
  • Ask Question
  • Contact Us
  • Home
  • PHP
  • Programming
  • SQL Injection
  • Web3.0

Friday, October 28, 2022

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

 October 28, 2022     arrays, c++, is-empty     No comments   

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)
  • Share This:  
  •  Facebook
  •  Twitter
  •  Stumble
  •  Digg
Newer Post Older Post Home

0 Comments:

Post a Comment

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

Total Pageviews

Featured Post

Why Learn PHP Programming

Why Learn PHP Programming A widely-used open source scripting language PHP is one of the most popular programming languages in the world. It...

Subscribe To

Posts
Atom
Posts
Comments
Atom
Comments

Copyright © PHPFixing