hey, i am trying to allocate a dynamic matrix on the heap and seems like i am doing something wrong.
i try to do the following thing :
vector< vector<int*> >* distancesMatrix=new vector< vector<int*> >;
it does allocate a matrix on the heap but the matrix itself is empty, i want the matrix to be sizeXsize but cant sort it alone
when not trying to allocate it on the heap with using
vector<vector<Distance*> > distance(size+1, vector<Distance*>(size+1, NULL));
thanks for your help
views:
82answers:
4A std::vector
keeps its data on the heap, even if the object itself is on the stack. I cannot imagine a scenario where you want a std::vector
itself to be on the heap. Do this:
vector< vector<int> > distancesMatrix;
and you're done.
That said, it might be better to wrap multi-dimensional class around a one-dimensional vector than nesting vectors.
I would suggest not using the vector-of-vectors approach for two reasons:
1) it allows the resulting data to be jagged (that is, any two rows may be different lengths). If you are wrapping this in a external interface or you just don't care, that may not be a problem, but:
2) the elements of the "matrix" are not going to be contiguous in memory, which can have a performance impact due to cache locality, reallocations, extra memory being used, et cetera. It may not be a big impact, but it's there.
Instead I would suggest you do this:
std::size_t size = 4; // Whatever you prefer.
std::vector<int> matrix( size * size );
You can then access the element at (x,y) using the following idiom:
int element = matrix[ x + y * size ];
The vector will allocate its elements on the heap, and they will be contiguous and this will also ensure the matrix is rectangular. You may want to wrap this in a class to provide a more natural interface.
If you really want to put the "matrix" itself on the heap, you can do so by making it a pointer and allocating it with new (or better, if you've wrapped the vector into your own class, say one called Matrix, put that on the heap instead).
Try:
#include <vector>
int main()
{
// Initialize the outside vector with 20 copies of a vector that contains 20 integers that are zero initialized.
std::vector<std::vector<int> > data(20, std::vector<int>(20));
data[10][10 = 5;
}