检查数组的所有元素 [英] Check all elements of an array
本文介绍了检查数组的所有元素的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!
问题描述
你好,
我想创建某种函数来检查数组的所有值,如果它们全部相同,则将bool设置为false,如果其中一个值不同,则其余值将bool设置为true.
示例:
假设array1包含{0,0,0},而array2包含{0,1,0}
Hello,
I would like to create some sort of function that checks all the values of an array and, if they are all the same, sets a bool to false, and if one of the values is different then the rest, sets the bool to true.
Example:
Say the array1 contains {0, 0, 0} and array2 contains {0, 1, 0}
int Array[3];
bool TheBool(false);
for(int i = 0; i < SizeOfArray; i++)
{
if(all elements of the array are the same)
{
TheBool = false;
}
else
{
TheBool = true;
}
}
对于array1,TheBool应为false,对于array2,则应为true.
预先感谢任何可以帮助我解决这个问题的人:)
With array1, TheBool should be false, and with array2, it should be true.
Thanks in advance to anyone who can help me out with this :)
推荐答案
一个幼稚的实现可能是这样的;
A naive implementation could be something like this;
#include <iostream>
using namespace std;
bool checkArray(int a[], size_t length)
{
if (length < 2)
return true;
else
{
int value = a[0];
for(int i = 1; i < length; ++i)
{
if (a[i] != value)
return false;
}
return true;
}
}
int main()
{
int myArray[3];
myArray[0] = 1;
myArray[1] = 2;
myArray[2] = 1;
cout << (checkArray(myArray, 3) ? "All are same" : "There are different numbers in there!") << endl;
return 0;
}
希望这会有所帮助,
弗雷德里克(Fredrik)
Hope this helps,
Fredrik
这篇关于检查数组的所有元素的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!
查看全文