本文介绍了检查数组的所有元素的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!
问题描述
你好, 我想创建某种函数来检查数组的所有值,如果它们全部相同,则将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
更多推荐
检查数组的所有元素
发布评论