Re: Comparing two objects
On Oct 16, 10:26 pm, Gus Gassmann <horand.gassm...@googlemail.com>
wrote:
I have complicated classes that I need to test for equality. An
example would be something like
class IndexValuePair
{
int dim;
int* index;
double* value;
}
class SparseMatrix
{
int numberOfColumns;
int* start;
IndexValuePair nonzeros;
}
In IndexValuePair, dim is the common size of the arrays index and
value; the array start in SparseMatrix has size numberOfColumns + 1.
I want to compare two sparse matrices. Two sparse matrices are equal
if they have the same number of columns, the start vectors match
component by component, and the IndexValuePairs are equal.
Two IndexValuePairs are equal if they have the same dimensions, the
components of index match one by one, and the components of value also
do.
(I know that strictly speaking I am allowed to reorder the indices
within a column, but I will and can assume that the indices are given
in ascending order within each column.)
Are there any library functions available that would let me do this?
Ideally I would like to be able to say
if (SparseMatrix1 == SparseMatrix2)...
or
if (equal(SparseMatrix1,SparseMatrix2)
I looked, but I have not been able to find anything useful.
(Be gentle, I am only a beginner...)
There is obviously no library function that can guess when two objects
of a given type compare equal in your case. Library, or the compiler,
hwever smart, can't read minds.
You can, however, overload operator= to do that.
e.g.
class IndexValuePair
{
int dim;
int* index;
double* value;
bool operator=(const IndexValuePair& rhs) const
{ // rhs: "right hand side" in e.g. "if (var1==var2) {...}"
if (dim != rhs.dim) return false;
for (int i=0; i<dim; ++i)
if (index[i] != rhs.index[i])
return false;
for (int i=0; i<dim; ++i)
if (value[i] != rhs.value[i]) // ^^^
return false;
return true;
}
};
Final note: line ^^^ is wrong, as one can't realistically compare
floating point numbers for equality.
Goran.
--
[ See http://www.gotw.ca/resources/clcm.htm for info about ]
[ comp.lang.c++.moderated. First time posters: Do this! ]