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 ?

Recommended Answers

All 6 Replies

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

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

You could also use memcmp

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.

@deceptikon: Yes. Good point. So there is also std::equal

Be a part of the DaniWeb community

We're a friendly, industry-focused community of developers, IT pros, digital marketers, and technology enthusiasts meeting, networking, learning, and sharing knowledge.