I am using extended sparse matrices containing bool and trying to write a comparison function to store them on a map. This is a very simple comparison function. In principle, the idea is to consider the matrix as a binary number (after smoothing into a vector) and sort based on the value of this number. This can be done as follows:
for(unsigned int j = 0; j < maxJ; j++)
{
for(unsigned int i = 0; i < maxI; i++)
{
if(matrix1(i,j) < matrix2(i,j) return true;
else if(matrix1(i,j) > matrix2(i,j) return false;
}
}
return false;
However, this is inefficient due to sparseness of matrices, and I would like to use iterators for the same result. The algorithm using iterators seems simple, i.e. 1) take the first nonzero cell in each matrix, 2) compare j * maxJ + i for both, 3) if they are equal, take the following nonzero cells in each matrix and repeat. Unfortunately, in the code, this is very tedious, and I'm worried about errors.
, (a) , () " " ? , , .
.
-
, , , , , . , , . - , , . , - .
typedef boost::numeric::ublas::mapped_matrix<bool>::const_iterator1 iter1;
typedef boost::numeric::ublas::mapped_matrix<bool>::const_iterator2 iter2;
// Grabs the next nonzero cell in a sparse matrix after the cell pointed to by i1, i2.
std::pair<iter1, iter2> next_cell(iter1 i1, iter2 i2, iter1 end) const
{
if(i2 == i1.end())
{
if (i1 == end)
return std::pair<iter1, iter2>(i1, i2);
++i1;
i2 = i1.begin();
}
else
{
++i2;
}
for(; i1 != end;)
{
for(; i2 != i1.end(); ++i2)
{
return std::pair<iter1, iter2>(i1,i2);
}
++i1;
if(i1 != end) i2 = i1.begin();
}
return std::pair<iter1, iter2>(i1, i2);
}