Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Should I reserve memory when using std::back_inserter

Tags:

c++

std

c++98

Do I need to reserve memory when using a back:inserter?

d.reserve(s.size())
std::copy (s.begin(),s.end(),back_inserter(d));
like image 418
Baz Avatar asked Oct 25 '13 07:10

Baz


People also ask

When to use std vector reserve?

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.

What does reserve do vector?

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 .

What does back inserter do c++?

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.


2 Answers

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.

like image 133
digital_revenant Avatar answered Oct 02 '22 01:10

digital_revenant


You don't have to. However, if this code snippet is run very frequently, you may consider reserving memory to improve performance.

like image 33
chys Avatar answered Oct 02 '22 02:10

chys