Search code examples
c++memory-managementsparse-matrix

std::vector<std::vector<type>> for sparse matrix structure or something else?


I am implementing a sparse matrix class in compressed row format. This means i have a fixed number of rows and each row consists of a number of elements (this number can be different for different rows but will not change after the matrix has been initialised.

Is it suitable to implement this via vectors of vectors or will this somehow fragment the memory?

How whould i implement the allocation of this so i will have one big chunk of memory?

Thanks for sharing your wisdom! Dirk


Solution

  • The general rule with sparse matrices is that you pick a structure that best fits the location of non-zeros in matrix; so maybe you could write a bit more about the matrix structure, and also what (sort of) algorithms will be invoked on it.
    About the memory -- if this matrix is not too big, it is better to alloc it as a one big chunk and make some index magic; this may result in a better cache use. If it is huge, then the chunked version should be used since it will better fit in memory.