Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Deque - how come "reserve" doesn't exist?

Tags:

c++

stl

The standard STL vector container has a "reserve" function to reserve uninitialized memory that can be used later to prevent reallocations.

How come that the other deque container hasn't it?

like image 822
Johnny Pauling Avatar asked Mar 20 '13 13:03

Johnny Pauling


People also ask

Does deque take more memory than vector?

Deque can have additional memory overhead over vector because it's made of a few blocks instead of contiguous one.

Is deque contiguous memory?

Elements in a deque are not contiguous in memory; vector elements are guaranteed to be. So if you need to interact with a plain C library that needs contiguous arrays, or if you care (a lot) about spatial locality, then you might prefer vector .

Is deque slower than vector?

The deque is a bit slower than the vector, that is logical because here there are more cache misses due to the segmented parts.

Is deque better than vector?

Vector provides good performance while insertion and deletion at end only and bad performance for insertion and deletion at middle. Deque provides same kind of performance as vector for insertion & deletion at end and middle. Apart from that deque provides good performance for insertion and deletion at front also.


2 Answers

Increasing the size of a std::vector can be costly. When a vector outgrows its reserved space, the entire contents of the vector must be copied (or moved) to a larger reserve.

It is specifically because std::vector resizing can be costly that vector::reserve() exists. reserve() can prepare a std::vector to anticipate reaching a certain size without exceeding its capacity.

Conversely, a deque can always add more memory without needing to relocate the existing elements. If a std::deque could reserve() memory, there would be little to no noticeable benefit.

like image 91
Drew Dormann Avatar answered Sep 21 '22 12:09

Drew Dormann


For vector and string, reserved space prevents later insertions at the end (up to the capacity) from invalidating iterators and references to earlier elements, by ensuring that elements don't need to be copied/moved. This relocation may also be costly.

With deque and list, earlier references are never invalidated by insertions at the end, and elements aren't moved, so the need to reserve capacity does not arise.

You might think that with vector and string, reserving space also guarantees that later insertions will not throw an exception (unless a constructor throws), since there's no need to allocate memory. You might think that the same guarantee would be useful for other sequences, and hence deque::reserve would have a possible use. There is in fact no such guarantee for vector and string, although in most (all?) implementations it's true. So this is not the intended purpose of reserve.

like image 37
Steve Jessop Avatar answered Sep 22 '22 12:09

Steve Jessop