简体   繁体   中英

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;
}

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.

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

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!

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

Just remove the "*" and it should work.

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