简体   繁体   English

垒球C ++问题:如何比较两个数组是否相等?

[英]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. 我试图比较两个int数组,逐个元素,以检查是否相等。 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. 注意:equal函数要求两个数组的大小相等。

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. 通常,使用std :: vector可以简化大多数代码。 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). 由于std :: vector重载了operator ==,因此在这种情况下,您所要做的只是if (a==b) ...即使在少数几个不适合使用vector的地方,TR1 :: array也会经常这样做作业(以及IIRC,它也提供了operator ==的重载)。

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. 当执行if(*ints[i] != obj.ints[i]) ,您要比较的是ints[i]指向的地址与obj.ints[i]的内容,而不是ints[i]的内容ints[i]本身。 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. 这是因为数组的名称已经是指向数组第一个元素的指针,并且当您添加下标时,将在该数组中第一个元素之后寻找第i个位置。 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 "}"? 我认为这全都由“类Object {”和“}”包裹了吗?

Just remove the "*" and it should work. 只需删除“ *”,它应该可以工作。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

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