C ++如何检查数组中的元素是否相等? [英] C++ how to check if elements in an array are equal?

查看:633
本文介绍了C ++如何检查数组中的元素是否相等?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我正在尝试编写一个程序,该程序使用for循环检查数组中的所有值是否相等,但是除了不断重复之外,我无法找出if语句检查数组中的每个值是否相等的方法"if a[i] == a[1] && a[i] == a[0]",依此类推.我不想这样做,因为我希望它适用于任何大小的任何数组.任何帮助深表感谢!

I am trying to write a program which checks if all the values in an array are equal using a for loop but I cannot figure out a way for the if statement to check if each value in the array are equal other than constantly repeating "if a[i] == a[1] && a[i] == a[0]" and so on. I do not want to do that as i want it to work for any array of any size. Any help is much appreciated!

    for (unsigned i = 0; i < val; i++){
       if (a[i] == a[0])
          return true;
       else
          return false;
    }

推荐答案

for (unsigned i = 0; i < val; i++) {
    if (a[i] != a[0]) {
        return false;
    }
}
return true;

应该这样做.

在这种情况下,代码将立即由于不匹配的值而失败.但是,对于匹配的值,它只会继续检查(众所周知,无论如何,我们都需要测试数组的每个元素).一旦完成,它就会知道一切顺利(因为我们没有提早返回)并返回true.

In this case, the code will instantly fail on a non-matching value. However, on a matching value it simply continues checking (as we know we need to test EVERY element of the array no matter what). Once that's done, it knows everything went well (since we didn't return early) and returns true.

这篇关于C ++如何检查数组中的元素是否相等?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆