开发者

stl vector reserve

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[开发者_如何学Cnode].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


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.


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;


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.

0

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜