Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Benefits of using reserve() in a vector - C++

What is the benefit of using reserve when dealing with vectors. When should I use them? Couldn't find a clear cut answer on this but I assume it is faster when you reserve in advance before using them.

What say you people smarter than I?

like image 620
Pladnius Brooks Avatar asked Jun 29 '11 18:06

Pladnius Brooks


People also ask

What does vector Reserve do?

vector::reserve() vector reserve() indicates that the vector is created such that it can store at least the number of the specified elements without having to reallocate memory. Begin Declare a variable v of vector type.

How does the vector member function resize () differ from reserve ()?

The main difference between vector resize() and vector reserve() is that resize() is used to change the size of vector where reserve() doesn't. reserve() is only used to store at least the number of the specified elements without having to reallocate memory.

Does vector Reserve take up memory?

vector::reserve does allocate memory, so your question about reserving memory without allocating is incorrect. The point is that reserving memory can be done without changing the vectors size. Basically a vector has two sizes, it's size and it's capacity.

What does vector Reserve do in C++?

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 .


2 Answers

It's useful if you have an idea how many elements the vector will ultimately hold - it can help the vector avoid repeatedly allocating memory (and having to move the data to the new memory).

In general it's probably a potential optimization that you shouldn't need to worry about, but it's not harmful either (at worst you end up wasting memory if you over estimate).

One area where it can be more than an optimization is when you want to ensure that existing iterators do not get invalidated by adding new elements.

For example, a push_back() call may invalidate existing iterators to the vector (if a reallocation occurs). However if you've reserved enough elements you can ensure that the reallocation will not occur. This is a technique that doesn't need to be used very often though.

like image 132
Michael Burr Avatar answered Sep 24 '22 11:09

Michael Burr


This excellent article deeply explains differences between deque and vector containers. Section "Experiment 2" shows the benefits of vector::reserve().

like image 20
gabrielmdu Avatar answered Sep 21 '22 11:09

gabrielmdu