Scott D
Scott D

Reputation:

Softball C++ question: How to compare two arrays for equality?

I am trying to compare two int arrays, element by element, to check for equality. I can't seem to get this to work. Basic pointer resources also welcome. Thank you!

int *ints;
ints = new int[10];

bool arrayEqual(const Object& obj)
{
    bool eql = true;

    for(int i=0; i<10; ++i)
    {
        if(*ints[i] != obj.ints[i])
            eql = false;
    }

    return eql;
}

Upvotes: 0

Views: 3840

Answers (4)

jpmelos
jpmelos

Reputation: 3562

When you do if(*ints[i] != obj.ints[i]), what you are comparing is the address pointed by ints[i] with the content of obj.ints[i], instead of the content of ints[i] itself. That is because the name of an array is already a pointer to the first element of an array, and when you add the subscript, you will look for the ith position after the first in that array. That's why you don't need the *.

The correct is:

int *ints;
ints = new int[10];

bool arrayEqual(const Object& obj)
{
    bool eql = true;

    for(int i=0; i<10; ++i)
    {
        if(ints[i] != obj.ints[i])
                eql = false;
    }

    return eql;
}

Hope I helped!

Upvotes: 2

Jerry Coffin
Jerry Coffin

Reputation: 490108

I'm surprised nobody's asked why you're using arrays in the first place. While there are places that arrays can be hard to avoid, they're few and far between. Most of your code will normally be simpler using std::vector instead. Since std::vector overloads operator==, all you have to do in this case is something like if (a==b) ... Even in the few places that vector isn't suitable, TR1::array will often do the job (and IIRC, it provides an overload of operator== as well).

Upvotes: 2

Keith Randall
Keith Randall

Reputation: 23265

I assume this is all wrapped by "class Object {" and "}"?

Just remove the "*" and it should work.

Upvotes: 0

Matthieu N.
Matthieu N.

Reputation:

how about the following?

#inlcude <algorithm>

bool arrayEqual(const Object& obj)
{
   return std::equal(ints,ints + 10, obj.ints);
}

Note: the equal function requires both arrays to be of equal size.

Upvotes: 15

Related Questions