2014-09-27 65 views
0

如何判断两个二维数组是否完全匹配每个元素?它们具有相同的尺寸。检查两个二维数组是否相等

std::equal似乎不起作用。

我试图写一个简单函数

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

但然后我需要两个阵列的最后一维传递一个二维阵列。这样做是否使用(sizeof(a[0])/sizeof(*(a[0])))

回答

1

假设您知道每个阵列的确切大小,并且它们在编译时已知,那么比较结果只是一个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); 

注意,我的代码假定两个阵列(a和b)具有相同的大小。你可以首先测试一下,用throw或者assert(比如std :: assert(sizeof(a)== sizeof(b)))。

如果您不知道编译时的大小sizeof将不起作用,因为它是编译时操作符,这意味着您必须通过尺寸或考虑使用stl

+0

您可以随时使用'sizeof a'版本 – 2014-09-28 02:25:35

+0

是的。 'sizeof a'总是可用的。但是,如果您执行了诸如“a = new int [32]”之类的操作,那么sizeof a将返回指针的大小,而不是数组的大小。 – 2014-09-28 20:53:20

2

也许这样吗?

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

MN应该是你的阵列的尺寸,或者你可以让他们的函数模板参数。不要忘记#include <array>

+0

所以你建议我使用'std :: array'而不是C数组,如果我想检查它们是否相等? – qwr 2014-09-27 23:57:34

+0

@qwr是的。 https://stackoverflow.com/questions/6111565/now-that-we-have-stdarray-what-uses-are-left-for-c-style-arrays – CoryKramer 2014-09-27 23:58:11

+0

@Cyber​​在我的C++程序中,我一直在使用数组在运行时大小。这是否意味着(根据http://stackoverflow.com/questions/737240/cc-array-size-at-run-time-wo-dynamic-allocation-is-allowed)我一直在使用无效的C++代码这整个时间? – qwr 2014-09-28 00:03:30