stl vector reserve

2019-08-01 04:04发布

问题:

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.