C++/How to compare 1D arrays inside of 2D arrays to check if they are equal.
Expert: Zlatko - 6/5/2010
QuestionHi Zlatko.
This is a program about to detect whether 2 rows are equal, not whether all of them are equal inside of 2D arrays and display them but it is not working. I am trying to detect what is wrong but I can not do it. Can you help me. This is the code. Thanks.
#include <iostream>
#include <iomanip>
using namespace std;
const int rows = 9;
const int cols = 5;
bool MyCompare(int*, int*, int);
void displayrowMatch(int[], int);
int main()
{
cout<<endl;
int array[rows][cols] = {{1,4,4,7,8},
{2,4,4,7,8},
{1,4,4,7,8},
{3,4,4,7,8},
{5,4,4,7,8},
{3,4,4,7,8},
{5,4,4,7,8},
{3,4,4,7,8},
{2,4,4,7,8}};
int comparison;
for(int i=0; i< rows; i++)
{
for(int j=0; j< cols; j++)
{
cout<<setw(7)<<array[i][j];
}
cout<<endl;
}
cout<<endl;
for(int i=0; i< rows; i++)
{
for(int j=i+1; j<rows; j++)
{
comparison = MyCompare(array[i], array[i+1], 5);
if(comparison == 1)
{
displayrowMatch(array[i], 5);
}
}
}
if(comparison == 0)
{
cout<<" It does not exist equals rows "<<endl;
}
cout<<endl;
return 0;
}
bool MyCompare(int* first, int* second, int numelements)
{
bool rowMatch=true;
for(int i=0; i<numelements; i++)
{
for(int j=i+1; j<numelements; j++)
{
for(int k=0; k<numelements && rowMatch;k++)
{
if(first[i]!=second[i]);
return false;
}
}
}
return true;
}
void displayrowMatch(int lineMatch[], int elements)
{
for(int i=0; i < elements; i++)
{
cout<<setw(7)<<lineMatch[i];
}
cout<<endl;
}
AnswerYour MyCompare function has a typing error.
You have
if(first[i]!=second[i]); <---- notice this semicolon at the end
return false;
The semicolon terminates the "if" statement, so the return false is not a consequent of the "if" statement. The "return false" will always happen. You need to remove the semicolon.
Set your compiler warning level higher and it might notify you of this type of error. I have not been able to get g++ to warn about it but the Microsoft compiler does.
The other problem is your comparison algorithm. You need to compare each array to every other array, not to just the array right after it. I think you knew that, you just had another typing error.
you want
comparison = MyCompare(array[i], array[j], 5); // notice the j instead of i+1
Also, declare comparison to be a bool, instead of an int, since MyCompare returns bool.
Best regards
Zlatko