Stuart said:
Daniel said:
Stuart Golodetz said:
Daniel T. wrote:
Daniel T. wrote:
For the latter, I think the Matrix class from the FAQ is a far
better choice than a vector of vectors of ints.
The one in FAQ 13.10 that stores doubles? ;-) But yes, in
practical use of course you'd encapsulate it. That being said, I'd
probably implement such a matrix class using a vector of vectors
in preference to doing it manually with new[] and delete[] as in
the FAQ (unless there was some compelling reason not to).
A single vector is better than either new[] delete[] or a vector of
vectors, unless you specifically want a ragged array.
Definitely better than new[] delete[]. Compared to vector of vectors:
+ Single vector involves one heap allocation rather than many
+ Single vector involves less overall memory overhead in terms of
storing sizes etc.
- You have to do your own indexing for 2D lookup with a single vector
What other advantages/disadvantages are there?
There are several questions in the FAQ that answer the question you ask,
starting with:
http://www.parashift.com/c++-faq-lite/operator-overloading.html#faq-13.11
But that's about the *interface* to a matrix class surely? I'm talking
about the *implementation* -- which can of course be easily changed
given a properly-designed interface. My original question still stands,
I think.
As for implementing a matrix class, what is "best" depends very much on
context. For instance, you could use a sparse matrix implementation to
conserve memory if most of your matrix entries are trivial. If the main
application is number crunching, a storage layout that eases arithmetic
operation (e.g., matrix multiplication, LU-decomposition, ...) may be
chosen. For instance, if you think of matrix multiplication, a flat layout
could be sub-optimal because of memory locality. What is most efficient, of
course, also depends very much on the multiplication algorithm used.
A more down-to-earth example where one can see the influence of the
representation on efficiency of operations: a vector of vector approach
would allow you to swap rows very efficiently (think of row-reduction to see
why this might be useful).
Given the vast problem space, it is virtually impossible to make an optimal
choice without knowing the specifics of the use-case. In C++, one can
implement the physical layout and memory management of a matrix class as a
policy to be determined by a template parameter. This way, you can have a
uniform interface with many underlying implementation strategies.
Best
Kai-Uwe Bux