1

How can I tell if two 2D arrays exactly match every element? They have equal dimensions.

std::equal does not seem to work.

I tried to write a simple function

bool arrays_equal(int a[][], int b[][])
{
...
}

but then I need the last dimension of both arrays to pass a two dimensional array. Would that be done using (sizeof(a[0])/sizeof(*(a[0])))?

qwr
  • 9,525
  • 5
  • 58
  • 102

2 Answers2

3

Maybe like this?

bool arrays_equal(std::array<std::array<int, M>, N> const & lhs,
                  std::array<std::array<int, M>, N> const & rhs)
{
    return lhs == rhs;
}

The values M and N should be your array dimensions, or you could make them function template parameters. Don't forget to #include <array>.

Kerrek SB
  • 464,522
  • 92
  • 875
  • 1,084
  • So you're suggesting I use `std::array` instead of C arrays if I want to check if they're equal? – qwr Sep 27 '14 at 23:57
  • @qwr Yes. https://stackoverflow.com/questions/6111565/now-that-we-have-stdarray-what-uses-are-left-for-c-style-arrays – Cory Kramer Sep 27 '14 at 23:58
  • @Cyber In my C++ programs I've been using arrays sized at runtime. Does that mean (according to http://stackoverflow.com/questions/737240/c-c-array-size-at-run-time-w-o-dynamic-allocation-is-allowed) I've been using invalid C++ code this whole time? – qwr Sep 28 '14 at 00:03
  • @qwr, did you mean 'arrays sized at compile time'? Because if only known at runtime, then Kerrek solution is certainly the best. Use either array or vector depending on your needs. However, if you have compile time arrays, then you cannot compare them unless you somehow pass the *various* sizes to your sub-functions. – Alexis Wilke Sep 28 '14 at 00:13
  • @AlexisWilke In fact, I had accidentally been using C99 variable length arrays. From what I can tell, `std::array` can't be sized at runtime so I guess I have to use a vector. – qwr Sep 28 '14 at 00:20
1

Assuming you know the exact size of each array and they are known at compile time, then the compare is just a memcmp() with the correct size.

// you somehow know the size of the array
int a[WIDTH][HEIGHT];
int b[WIDTH][HEIGHT];

bool const equal(memcmp(a, b, sizeof(int) * WIDTH * HEIGHT) == 0);

// and if defined in the same scope, you can even use:
bool const equal(memcmp(a, b, sizeof(a)) == 0);

Note that my code assumes that both arrays (a and b) have the same size. You could test that first to make sure, with a throw or maybe an assert such as std::assert(sizeof(a) == sizeof(b)).

In case you don't know the size at compile-time sizeof won't work since it's a compile-time operator, which means you'll have to pass the dimensions or consider using stl.

Alexis Wilke
  • 19,179
  • 10
  • 84
  • 156
  • You can always use the `sizeof a` version – M.M Sep 28 '14 at 02:25
  • Yes. `sizeof a` is always available. However, if you did something such as `a = new int[32]` then `sizeof a` returns the size of the pointer, not the size of the array. – Alexis Wilke Sep 28 '14 at 20:53