Reputation: 1838
I know that deque is more efficient than vector when insertions are at front or end and vector is better if we have to do pointer arithmetic. But which one to use when we have to perform insertions in middle.? and Why.?
Upvotes: 11
Views: 4153
Reputation: 227618
std::deque could perform better for large containers because it is typically implemented as a linked sequence of contiguous data blocks, as opposed to the single block used in an std::vector
. So an insertion in the middle would result in less data being copied from one place to another, and potentially less reallocations.
Of course, whether that matters or not depends on the size of the containers and the cost of copying the elements stored. With C++11 move semantics, the cost of the latter is less important. But in the end, the only way of knowing is profiling with a realistic application.
Upvotes: 1
Reputation: 308538
You might think that a deque
would have the advantage, because it stores the data broken up into blocks. However to implement operator[]
in constant time requires all those blocks to be the same size. Inserting or deleting an element in the middle still requires shifting all the values on one side or the other, same as a vector
. Since the vector
is simpler and has better locality for caching, it should come out ahead.
Upvotes: 14
Reputation: 206656
Selection criteria with Standard library containers is, You select a container depending upon:
If you want to perform large number of insertions in the middle you are much better off using a std::list
.
If the choice is just between a std::deque
and std::vector
then there are a number of factors to consider:
max_size()
might be larger for deques.Upvotes: 3
Reputation: 3744
Deque would still be more efficient, as it doesn't have to move half of the array every time you insert an element.
Of course, this will only really matter if you consider large numbers of elements, and even than it is advisable to run a benchmark and see which one works better in your particular case. Remember that premature optimization is the root of all evil.
Upvotes: 0