Do I need to reserve memory when using a back:inserter?
d.reserve(s.size())
std::copy (s.begin(),s.end(),back_inserter(d));
Using std::vector::reserve whenever possibleVectors are assigned memory in blocks of contiguous locations. When the memory allocated for the vector falls short of storing new elements, a new memory block is allocated to vector and all elements are copied from the old location to the new location.
vector::reserveIncrease the capacity of the vector (the total number of elements that the vector can hold without requiring reallocation) to a value that's greater or equal to new_cap .
A back-insert iterator is a special type of output iterator designed to allow algorithms that usually overwrite elements (such as copy) to instead insert new elements automatically at the end of the container.
You do not need to reserve memory for the container when using std::back_inserter
. However, if you know beforehand about the number of elements you are going to insert and want to prevent repeated allocations you may reserve memory.
You don't have to. However, if this code snippet is run very frequently, you may consider reserving memory to improve performance.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With