tags:

views:

69

answers:

2

Hello, i'm trying to initialize all cells of a matrix with NULL values, but something is wrong here.
the code :

vector<vector<Distance*> > distanceMatrix;  
    for (int i = 0; i < 7 ; i++)
        for (int j = 0; j < 7 ; j++)
            distanceMatrix[i][j].push_back(NULL);  

i bet it's something stupid, thanks for the help.

+8  A: 

From the std::vector reference page:

Vectors can be constructed with some values in them.

You may try:

vector<vector<Distance*> > distanceMatrix(7, vector<Distance*>(7, NULL));

Also, regarding your problem:

vector<vector<Distance*> > distanceMatrix;  
    for (int i = 0; i < 7 ; i++)
        for (int j = 0; j < 7 ; j++)
            distanceMatrix[i][j].push_back(NULL); //1

When you code first reach //1, distanceMatrix[i] resolves to distanceMatrix[0] but you did not call distanceMatrix.push_back(vector<Distance*>()) so you are referring to a non initialized cell.

To correct code would have been:

vector<Distance*> vec;

for (int j = 0; j < 7 ; j++)
  vec.push_back(NULL);

vector<vector<Distance*> > distanceMatrix;

for (int i = 0; i < 7 ; i++)
{
    distanceMatrix.push_back(vec);
}

Which is still far worse than my first suggestion.

ereOn
@ereOn - is the NULL required for vector of pointers? What would default value be here?
Steve Townsend
@Steve Townsend: You're right, `NULL` is probably the default. However, I wanted to make it more explicit what parameters the constructor takes.
ereOn
@ereOn - absolutely, just curious. Never use vectors of ptrs myself.
Steve Townsend
+1  A: 

Since the matrix is empty to begin with, you need to push_back every value and every row, not depending on its position in the matrix:

vector<Distance*> row;
for(int j=0; j < 7; j++)
    row.push_back(NULL);

vector<vector<Distance*> > distanceMatrix; 
for(int i=0; i < 7; i++)
    distanceMatrix.push_back(row);
You
`push_back(new vector<Distance*>(row));` creates a dynamic vector that's only used momentarily for initialising distanceMatrix, then leaked... :-/.
Tony
This approach (if fixed) would imply a lot of row copying, bothersome for larger matrices than the 7x7 here
Steve Townsend
I was thinking "I'd better copy this", but meh. I fail ;)
You
@You - happens to me all the time (well, a lot) - a great learning experience...
Steve Townsend