I've started reading C++ Primer a few weeks ago and there's an exercise that asks you to compare two arrays for equality. The code I made works, but is it good? What should I fix?
If the number of elements don't match, they're not equal. If the elements are different, they are not equal.
#include <iostream>
using namespace std;
bool arrayComparer(int *a, size_t asize, int *b, size_t bsize){
if(asize != bsize){return false;}
for(size_t ite = 0; ite < asize; ++ite){
if(*(a+ite) != *(b+ite)){return false;}
}
return true;
}
int main()
{
int ar1[]{0,1,2,3,4,5,6,7,8,9},
*ptr1 = ar1,
ar2[]{0,1,2,3,4,5,6,7,8,9,10,11,12,13,14,15,16,17,18},
*ptr2 = ar2;
size_t intSize = sizeof(int),
asize = sizeof(ar1) / intSize,
bsize = sizeof(ar2) / intSize;
cout << arrayComparer(ptr1,asize,ptr2,bsize) << endl;
return 0;
}
Since the number of elements may be different, I'm using pointers. I did not find a way to get the number of elements from the pointers, so I'm also passing the size to the function.
Comments are appreciated.
std::equal(ar1, ar1 + 10, ar2 + ar2 + 19).
\$\endgroup\$ar1 == ar2
also work if they were bothstd::array
s (and of equal size)? \$\endgroup\$std::array
'soperator==
does indeed do an element wise comparison. I would preferstd::equal
though because it would allow him to later change either of the types involved without having to change the comparsion (If he usedstd::begin()
instead of.begin()
). (Also,std::array
is C++11 which he might not be used.) \$\endgroup\$