Reputation: 39284
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 memcmp call.
Upvotes: 5
Views: 5742
Reputation: 39558
std::array
(C++11)std::array<int> x = {1, 2, 3, 4};
std::array<int> y = {1, 2, 3, 4};
if (x == y) // true
std::array
avoids a lot of C-style array problems in general, so you might want to replace all your uses of int[]
with it.
std::span
s(C++20)if (std::span{x} == std::span{y})
std::span
is a lightweight non-owning view into an array.
Wrapping a range in a std::span
and using the ==
operator should be just as cheap as using standard library algorithms.
std::equal
(C++98) or std::ranges::equal
(C++20)if (std::ranges::equal(x, y))
// the last argument is optional, but may be helpful for optimizations
if (std::equal(std::begin(x), std::end(x), std::begin(y), std::end(y))
Upvotes: 0
Reputation: 170839
You can use the standard std::equal
algorithm (or std::ranges::equal
since C++20):
if (std::equal(x, std::end(x), y)) cout << "It worked!";
// or since C++20
if (std::ranges::equal(x, y)) cout << "It worked!";
Upvotes: 20
Reputation: 57678
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";
}
Upvotes: 1
Reputation: 361362
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!
Upvotes: 11
Reputation: 5164
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.
Upvotes: -1
Reputation: 9685
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.
Upvotes: 8