3

I know how much space I initially need in a std::vector. So I use .resize() to set the new vector to that size. But when using .push_back() afterwards, it adds the elements at the end of the allocated size increasing it by one.

How can I add new elements automatically in the empty placed of a resized vector?

danijar
  • 32,406
  • 45
  • 166
  • 297

2 Answers2

7

How can I add new elements automatically in the empty placed of a resized vector?

That is what you are doing. resize fills the new space with value-initialized elements, so there are no "empty places". It seems like you need to call std::vector::reserve instead.

std::vector<int> v{1,2,3,4}; // size = 4
v.reserve(100); // size = 4, capacity = 100
v.push_back(5); // no re-allocations. size  5.
juanchopanza
  • 223,364
  • 34
  • 402
  • 480
3

By using the method reserve instead of resize, your push_back will do the job without reallocating memory.

rems4e
  • 3,112
  • 1
  • 17
  • 24