简体   繁体   English

检查所有int数组元素是否都等于特定数字的最短代码?

[英]Shortest code to check if all int array elements are equal to a specific number?

What's the shortest way I can do an if..else statement to check if all int array elements are equal to certain numbers? 我可以执行if..else语句来检查所有int数组元素是否等于某些数字的最短方法是什么? For example in pseudocode: 例如在伪代码中:

if (allElementsOfIntArray == -1)
   //do something
else if (allElementsOfIntArray == 1)
  //do something else

I have another variable that is const int arraySize 我还有另一个变量const int arraySize

My Arduino code is getting really messy at this point so I'm just trying to find the shortest way to implement this so it doesn't look like a mess to others that have to read it. 我的Arduino代码在这一点上变得非常混乱,所以我只是想找到实现此问题的最短方法,因此对于其他必须阅读它的人来说,它看起来并不混乱。

bool all_are(int* i_begin, std::size_t sz, int x)
{
    const int* i_end = i_begin + sz;
    for(; i_begin != i_end; ++i_begin)
        if(*i_begin != x) return false;

    return true;
}

if (all_are(my_array, arraySize, -1))
   //do something
else if (all_are(my_array, arraySize, 1))
  //do something else

Check first if all entries are the same and then switch() : 首先检查所有条目是否相同,然后检查switch()

for (int i=1; i<arraysize; i++)
   if (theArray[0] != theArray[i]) return "no way";

/*** All array elements are the same, so we can evaluate any element ***/

switch (theArray[0]) 
{
   case 0:
        return "All are zero";
   case 1:
        return "All are one";
   default:
        return "All elements are the same";
}

The quickest way that pops into mind (assuming the array is unsorted) is to just iterate through it and checking each element. 想到的最快方法(假设数组未排序)只是对其进行迭代并检查每个元素。 You can do this a few ways. 您可以通过几种方法来执行此操作。 Use a normal for loop or try a for each . 使用正常的for循环或for each尝试一个。

Each element in array is independent to others. 数组中的每个元素都相互独立。 So you must use for to check all of it to make sure. 因此,您必须使用进行检查以确保所有内容。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

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