Reputation: 9645
I am looking for a way to have a Matrix variable (i.e, a bunch of ordered column vectors) which is contiguous in memory, using an STL container (e.g, an std::vector). One option is this:
vector< vector<float> > mat;
mat.push_back (column1); // column1 is of type vector<float>
mat.push_back (column2); // column2 is of type vector<float>
which is not contiguous in the sense that &mat[1][0]
is not equal to &mat[0][N-1] + 1
, where N
is the length of column1
.
Another option is this:
vector< float > mat;
float f1[] = {1., 2., 3.};
float f2[] = {4., 5., 6.};
mat.insert (mat.end (), f1, f1 + 3);
mat.insert (mat.end (), f2, f2 + 3);
Which is contiguous in memory, but enforces me to use an array of floats.
EDIT
TO make it clear, I prefer an option like vector < vector<float> >
, so I can access a given column as an STL vector.
Upvotes: 1
Views: 1154
Reputation: 227418
To ensure that the data is indeed contiguous, I think you need to base it on a single array-type object, with static or dynamic size depending on your requirements, and take care of all the book-keeping and access. Have a look at boost matrices. A while back I worked on static-sized matrices and although I don't suggest that you use that stuff, it is an (old.fashioned) example of how it can be done.
Upvotes: 2
Reputation: 1839
Subclass a vector<float>
. Make of of size rowSize*colSize
. The memory is contiguous since it is one single vector.
For the part on accessing columns as vectors, consider instead, accessing columns using two iterators to mark the range of the column. Modify your algorithms on columns to work with RandomAccessIterator
conforming iterators, or wrap the two iterators using a Column
class that computes the address from the start iterator in T& operator[](size_t)
.
Upvotes: 2
Reputation:
See if this helps you (probably you have to modify the source code if you want column-major storage).
Upvotes: 0
Reputation: 17186
You can't do this trivially with the standard library as far as I know, but you could always use Boost's multidimensional arrays.
Upvotes: 2
Reputation: 52539
I would write my own matrix class which uses a std::vector<float>
as backend for storage.
Upvotes: 3