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

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

我可以执行 if..else 语句来检查所有 int 数组元素是否都等于特定数字的最短方法是什么?例如在伪代码中:

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

我有另一个变量是 const int arraySize

我的 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

想到的最快方法(假设数组未排序)是遍历它并检查每个元素。您可以通过几种方式做到这一点。使用正常的 for 循环或尝试 for each

首先检查所有条目是否相同,然后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";
}

数组中的每个元素都相互独立。所以你必须使用for来检查所有这些以确保。