Вы можете легко сделать универсальную версию, которая позволяет матрицы с любым количеством измерений любого размера любого типа.Вы можете сделать размер массива параметром шаблона, чтобы вам не приходилось его передавать.
#include <type_traits>
#include <cstddef>
template<class T, std::size_t N>
typename std::enable_if<!std::is_array<T>::value, bool>::type
equal(T (&a)[N], T (&b)[N]) {
for (std::size_t i = 0; i < N; ++i) {
// T is not an array, (a is a single dimension array)
// so just compare the values.
if (a[i] != b[i]) {
return false;
}
}
return true;
}
template<class T, std::size_t N>
typename std::enable_if<std::is_array<T>::value, bool>::type
equal(T (&a)[N], T (&b)[N]) {
for (std::size_t i = 0; i < N; ++i) {
// T is an array (So a is a multidimensional array)
// recursively call the "equal" function on the
// lower dimensional arrays.
if (!equal(a[i], b[i])) {
return false;
}
}
return true;
}
Например:
#include <iostream>
int main() {
// Modified the size so you can see it better
int matrixOne[2][3] = { { 1, 2, 8 }, { 3, 4, 9 } };
int matrixTwo[2][3] = { { 1, 2, 8 }, { 3, 4, 9 } };
/*
equal(matrixOne, matrixTwo)
// bool equal<int[3], 2> equal(int[3][2], int[3][2]);
is equivalent to:
equal(matrixOne[0], matrixTwo[0]) && equal(matrixOne[1], matrixTwo[1])
// bool equal<int, 3> equal(int[3], int[3]);
And they just compare the 3 values per column
*/
// prints 1
std::cout << equal(matrixOne, matrixTwo) << '\n';
}
Но, поскольку функциипросто многомерный массив "int", вы можете просто std::memcmp
.
#include <type_traits>
#include <cstddef>
#include <cstring>
// Change the above to
template<class T, std::size_t N>
typename std::enable_if<
!std::is_array<T>::value && !std::is_trivially_copyable<T>::value, bool
>::type
equal(T (&a)[N], T (&b)[N]);
template<class T, std::size_t N>
typename std::enable_if<
std::is_array<T>::value && !std::is_trivially_copyable<T>::value, bool
>::type
equal(T (&a)[N], T (&b)[N]);
// And the new one for trivial types
template<class T, std::size_t N>
typename std::enable_if<std::is_trivially_copyable<T>::value, bool>::type
equal(T (&a)[N], T (&b)[N]) noexcept {
return std::memcmp(a, b, sizeof(a)) == 0;
}