stl vector reserve

对着背影说爱祢 提交于 2019-12-24 09:49:36

问题


I was trying to pre-allocate a vector of integer like this

vector<int> tmp_color; tmp_color.reserve(node_obj[node].c_max);
    for(int tmp_color_idx = 0; tmp_color_idx < node_obj[node].c_max; tmp_color_idx++)
         tmp_color[tmp_color_idx] = tmp_color_idx;

where node_obj[node].c_max is > 0 (I checked). size of tmp_color appears to be zero anyways, after the for loop. If there something wrong with the code?

Thanks


回答1:


If you want to make assignments in the loop as you wrote I suggest the following way:

vector<int> tmp_color(node_obj[node].c_max);
for(int tmp_color_idx = 0; tmp_color_idx < node_obj[node].c_max; tmp_color_idx++)
     tmp_color[tmp_color_idx] = tmp_color_idx;



回答2:


reserve does not actually add elements to a vector; that's what resize does. reserve just reserves space for them. You either need to add the elements one-by-one in your loop, using:

tmp_color.push_back(tmp_color_idx);

or change your use of reserve to resize.




回答3:


You are rather lucky that it didn't crash.

tmp_color[tmp_color_idx] = tmp_color_idx;

In the above line, you are accessing out of bounds of the vector.

reserve() doesn't increase the size of the vector, resize() should be used. To me, the method used by Elalfer is even better to pre-allocate the size.



来源:https://stackoverflow.com/questions/4765910/stl-vector-reserve

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!