How to insert after the last element of a resized std::vector?

1k views Asked by At

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?

2

There are 2 answers

0
juanchopanza On BEST ANSWER

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.
0
rems4e On

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