Eigen gotcha, sparse matrix inneriterator type

I just experienced a really annoying Eigen gotcha. If I have a sparsematrix A, defined as:


SparseMatrix<double> A;
// ... filled in somehow

then I can loop over the values with:


for(int k=0; k<A.outerSize(); ++k)
{
  // Iterate over inside
  for(SparseMatrix<double>::InnerIterator it (A,k); it; ++it)
  {
      // it.row(),  it.col(), it.value()
  }
}

This works fine. But if instead I use the wrong type for the InnerIterator, say int, I get no complaint from the compiler, just occasional garbage when I use it.col(), it.row(), or it.value():


for(int k=0; k<A.outerSize(); ++k)
{
  // Iterate over inside
  for(SparseMatrix<int>::InnerIterator it (A,k); it; ++it)
  {
      // it.row(),  it.col(), it.value() produce occasional garbage
  }
}

Tags: , , , , ,

Leave a Reply