执行 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
关于c - 检查所有 int 数组元素是否等于特定数字的最短代码?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/40937980/