tags:

views:

82

answers:

4

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

A: 

Try vector< vector<int> >(size, size).

genpfault
Should that not be: `vector<vector<int> > data(size, vector<int>(size));`
Martin York
That will work too, yeah.
genpfault
@genpfault: No, not "too". Yours does not work.
GMan
@GMan: How so? [This](http://pastebin.com/sKmY3GGB) builds/executes fine for me using g++ 4.2.1 on FreeBSD. What am I missing?
genpfault
+3  A: 

A 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.

sbi
Imagined scenario: Passing ownership of the matrix from one thread to another.
John Dibling
@John: I think you can use auto_ptrs to do that.
Brian
@Brian: At some level, the `auto_ptr` would need to be relase()ed
John Dibling
+1  A: 

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).

Josh Petrie
+1  A: 

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;
}
Martin York