简体   繁体   English

检查两个2D数组是否相等

[英]Check if two 2D arrays are equal

How can I tell if two 2D arrays exactly match every element? 如何确定两个2D数组是否与每个元素完全匹配? They have equal dimensions. 它们具有相等的尺寸。

std::equal does not seem to work. std::equal似乎不起作用。

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]))) ? 可以使用(sizeof(a[0])/sizeof(*(a[0])))吗?

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. MN应该是您的数组尺寸,也可以使它们成为函数模板参数。 Don't forget to #include <array> . 不要忘记#include <array>

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. 假设您知道每个数组的确切大小,并且在编译时就知道它们,那么比较只是大小正确的memcmp()

// 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. 请注意,我的代码假定两个数组(a和b)具有相同的大小。 You could test that first to make sure, with a throw or maybe an assert such as std::assert(sizeof(a) == sizeof(b)). 您可以先进行测试以确保确定,例如可以使用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 . 如果您不知道在编译时使用sizeof因为它是一个编译时运算符就不会起作用,这意味着您必须传递尺寸或考虑使用stl

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

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