简体   繁体   English

比较两个 Integer Arrays 是否相等

[英]To Compare two Integer Arrays are equal Or Not

#include <iostream>
using namespace std;

bool equal_arr(int* arr, int* arr2, int m, int n)
{
    if (m != n)
    {
        return false;
    }
    int i = 0, j = 0;
    bool res = false;
    while (i < n)
    {
        if (arr[i] == arr2[j])
        {
            res = true;
            i++;
            j++;
        }
        else
        {
            i++;
            j++;
            res = false;
        }
        return res;
    }
}

int main(void)
{
    int arr[5] = { 4, 4, 4, 4, 4 };
    int arr2[5] = { 4, 5, 2, 8, 6 };
    if (equal_arr(arr, arr2, 5, 5))
        cout << "true" << endl;
    else
        cout << "false";
    return 0;
}

the above code should print true or false while comparing between two arrays, but it gives a wrong output while at any occurance if both element between the arrays is same it returns true for some logical issues,in my sample testcase you can see it.上面的代码在两个 arrays 之间进行比较时应该打印 true 或 false,但它给出了错误的 output,而在任何情况下,如果 arrays 之间的两个元素是相同的,你可以看到它在一些逻辑问题中返回 true。

Your logic is wrong.你的逻辑是错误的。 This这个

        if (arr[i] == arr2[j])
        {
            res = true;
            i++;
            j++;
        }
        else
        {
            i++;
            j++;
            res = false;
        }

would make your comparison function return the comparison of the last elements, because with each iteration you are overriding the previous result.将使您的比较 function 返回最后一个元素的比较,因为每次迭代都会覆盖先前的结果。 And the return statement in the end of the loop makes it even less clear: you are always comparing only first element (because you return after the first iteration).循环末尾的return语句使它变得更加不清晰:您总是只比较第一个元素(因为您在第一次迭代后返回)。

Better like this:最好像这样:

for (int i = 0; i < n; i++)
{
    if (arr[i] != arr2[i]) return false;
}
return true;

because just one pair of elements that are not equal is enough to return false .因为只有一对不相等的元素就足以返回false

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM