检查数组的所有元素

编程入门 行业动态 更新时间:2024-10-19 20:32:18
本文介绍了检查数组的所有元素的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧! 问题描述

你好, 我想创建某种函数来检查数组的所有值,如果它们全部相同,则将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

更多推荐

检查数组的所有元素

本文发布于:2023-10-24 19:59:40,感谢您对本站的认可!
本文链接:https://www.elefans.com/category/jswz/34/1524861.html
版权声明:本站内容均来自互联网,仅供演示用,请勿用于商业和其他非法用途。如果侵犯了您的权益请与我们联系,我们将在24小时内删除。
本文标签:数组   元素

发布评论

评论列表 (有 0 条评论)
草根站长

>www.elefans.com

编程频道|电子爱好者 - 技术资讯及电子产品介绍!