简体   繁体   English

std::vector resize() 仅在 clear() 后有效

[英]std::vector resize() works only after clear()

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?这是预期的行为吗?

From the docs for vector::resize :来自vector::resize的文档:

_Val: The value of new elements added to the vector if the new size is larger that the original size. _Val:如果新大小大于原始大小,则添加到向量中的新元素的值。

Only the new rows get vectors with additional columns ( std::vector<MyReal>(_colms) ).只有新行获得带有附加列的向量( std::vector<MyReal>(_colms) )。 resize will not change the existing rows. resize不会更改现有行。

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

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM