简体   繁体   中英

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.

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. 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).

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 .

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

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