0

Have a question , if we can compare two arrays for equality like this

#include <iostream>

using namespace std;

int main() {
    int a[5],b[5];
    for (int i=0;i<5;i++) {
        cin>>a[i];
        cin>>b[i];
    }
    if (a==b) cout<<"they are equal";

}

as you see isnt there a way like this or a function to do this ?

4
Contributors
6
Replies
7
Views
5 Years
Discussion Span
Last Post by L7Sqr
0

as you see isnt there a way like this or a function to do this ?

The comparison operator doesn't work for arrays. Use a loop and write your own function:

int compare_array(int a[5], int b[5])
{
    for (int i = 0; i < 5; ++i) {
        if (a[i] != b[i])
            return a[i] < b[i] ? -1 : +1;
    }

    return 0;
}

This can be generalized with templates, but I won't overwhelm you with what ultimately looks like line noise. ;)

0

As an aside, C++11 provides an array class which comes with a lot of functionality, if you have a compiler that supports it.

0

You could also use memcmp

You could, and it might work, but it's not guaranteed for anything but arrays of character type. See if you can figure out why. I'm really busy right now and can't elaborate.

This topic has been dead for over six months. Start a new discussion instead.
Have something to contribute to this discussion? Please be thoughtful, detailed and courteous, and be sure to adhere to our posting rules.