Search code examples
c++eigeneigen3

random (read only) access to elements of Eigen::SparseVector


Consider the following silly code piece

typedef Eigen::SparseVector<std::complex<double>, Eigen::ColMajor,long long> Vector;

Vector V = CreateData();

for(i=0;i<V.size(),++i)
{
  DoSomething( Vector.coeffRef(i));
}

I'm kind of interesting (for some purpose) to access (say) every elements of sparse vector V and expect, of course, zero to be returned when accessing non initialized entries.

What I'm surprisingly found is that at the access to a non existing\initialized entry, this entry is being created on reading, with the correct value of zero of course, but why???

I'm definitely not interesting in such behavior. All I want to get is zero returned whenever a non initialized entry being accessed for reading, otherwise a cast to full matrix is faster. Is there an alternative to .coeffRef that won't allocate new entries.


Solution

  • Use the coeff() method instead of the coeffRef() one. It does exactly what you want. On the other hand, coeffRef() returns a reference for read-write access, so the element must exist.