Accessing the indices of non-zero elements in a UBLAS sparse vector
How can I know the index of the first non-zero element in a sparse_vector in 开发者_运维问答ublas and each subsequent nonzero element as well? The function begin() gives me an iterator that can be used to know the first non-zero value stored, not its index in the vector.
Here is the answer, after Oswin Krause, from the ublas mainling list:
Iterators offer a method index() which returns the desired result. But remember that only the const_iterator is really sparse!
for(SparseVector::const_iterator pos = sparseVec.begin(); pos != sparseVec.end();++pos){ std::cout << pos.index()<< " "<< *pos; }
This seems impossible to achieve without a linear scan over the vector. The API simply doesn't expose the non-zero indices. (I'd write to the authors if I were you, since they are withholding information that can be very useful when serializing sparse vectors.)
I've had similar problems with UBLAS's sparse matrices in the past, eventually forcing me to roll my own.
精彩评论