开发者

Array contents equality in C++

Is there a way to get the equality operators to work for comparing arrays of the same type?

For example:

int x[4] = {1,2,3,4};
int y[4] = {1,2,3,4};
int z[4] = {1,2,3,5};
if (x == y) cout << "It worked!"

I'm aware that as is, it's just comparing pointer values - but I was hoping there's some kind of typedef trick or something like that so it wouldn't need a loop or a mem开发者_Python百科cmp call.


You can use standard equal algorithm

if (std::equal(x,x+4,y)) cout << "It worked!";


Use std::equal as:

if(std::equal(x, x+ xsize, y)) std::cout << "equal";

It checks equality of elements in the same order. That means, according to std::equal the following arrays are not equal.

int x[4] = {1,2,3,4};
int y[4] = {1,2,4,3}; //order changed!


Another way would be to wrap your arrays in the std::array template, which will make a small wrapper class for the array. Everything works pretty much like normal, except that you get a default definition of operator=, so you can use == as normal to do the expected thing.


Since the arrays are of the same type and length, you could use memcmp to test for equality, that is equality of value and position:

int array1[4] = {1, 2, 3, 4};
int array2[4] = {5, 6, 7, 8};

if (memcmp(array1, array2, sizeof(array1)) == 0)
{
    cout << "arrays are equal" << "\n";
}
else
{
    cout << "arrays are not equal" << "\n";
}


I think its also useful to note here that C++ does not allow you to overload operator== without at least 1 user-defined type. That would be the "nice" solution, but even if you could, it would probably be a bad idea. Arrays in C++...are sort of evil woodland creatures.

std::equal is probably your best bet. Though you could probably do what you want with a *gasp* macro, i think that is gacky.

0

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜