简体   繁体   中英

C++ Integer array and boolean functions

I need to write in C++ a complete boolean function that will take an integer array and it's maximum size as a parameter and return whether or not that array has any elements with a value of 0.

I'm not even sure where to start.

Thanks in advance.

bool checkFunction(int *myArray, int size)
{
    for (int i=0; i < size; ++i)
    {
        if (myArray[i] == 0)
            return true;
    }

    return false;
}

Are you talking about something like this? This will iterate through the array and return true if there is a value of 0 anywhere.

Use std::find

#include <algorithm>

bool ContainsZero(int *arr, int size)
{
   return std::find(arr, arr+size, 0) != (arr+size);
}

如何在C ++中阅读有关数组的教程?

bool TestForZero(int* myArray, int maxSize)
{
    for(int ii=0; ii<maxSize; ++ii)
      if(myArray[ii] == 0)
        return true;

  return false;
}

This sounds an awful lot like a homework problem, so I'll just give you the concepts and let you learn.

You need to use a "for" loop, check the value of each item in the array, and return true if you find one, otherwise return false after the loop exits.

bool hasZeroes(int * array, int len) {
  int zeroCount = 0;
  for (int i = 0; i < len; i++) {
    if (array[i] == 0) zeroCount++;
  }
  return zeroCount > 0;
}
bool foo(int* array, int size)
{
    int i;
    for (i = 0; i < size; i++)
    {
        if (array[i] == 0)
        {
            return true;
        }
    }

    return false;
}

and to call it you would do something like:

int arr[] = { 1, 2, 3, 4, 0, 6};

foo(arr, 6);

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM