views:

87

answers:

1

I have a vector object:

std::vector<std::vector<MyClass>> _matrix;

It is 2d array with some data. When i trying to resize the dimensions with:

_matrix.resize(_rows, std::vector<MyReal>(_colms)); //_rows and _colms are ints

this command simply does nothing to the object. So to resize it i have to call first to:

_matrix.clear();

and then:

_matrix.resize(_rows, std::vector<MyReal>(_colms)); 

Of course, I'm losing the data. (In my case it doesn't matter)

Is this expected behaviour?

+5  A: 

From the docs for vector::resize:

_Val: The value of new elements added to the vector if the new size is larger that the original size.

Only the new rows get vectors with additional columns (std::vector<MyReal>(_colms)). resize will not change the existing rows.

Update: To resize the entire vector properly, iterate over the existing rows and resize those vectors, then add the new rows. Something like this should work:

for (size_t i = 0; i < _matrix.size(); i++)
  _matrix[i].resize(_colms);
_matrix.resize(_rows, std::vector<MyReal>(_colms));
casablanca
You are right. Is there is a way to resize to new rectangular size?
Sanich
@Sanich: See my updated answer.
casablanca
OK, I understand now the functionality of resize. In my case, when I don't mind losing the data, using clear() is more simple. Thanks.
Sanich