Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Vector vs Deque operator[]

Tags:

c++

vector

deque

Deques are to be chosen over vectors if we are constantly adding in front and in the back of the container. But what about offseting? Do vector's and deque's operator[] work the same, or not? If not, which one is faster?

like image 210
user2653125 Avatar asked Sep 15 '13 11:09

user2653125


People also ask

What is difference between vector and deque?

Deque is a type of data structure that allows for the insertion and deletion of elements at the middle, end, and beginning. Vector is a type of data structure that allows for insertion and deletion of elements within the Data structure using the method at the middle of the end.

When would you use a deque in preference to a vector?

One should choose deque over vector if he wants to either add or delete from both the ends like implementing a Queue.

Which is faster deque or 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.

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.


1 Answers

A std::vector<T> is a flat array of T elements. std::deque<T> is an array of equal sized arrays of T. The complexity of index access is O(1) in both cases but std::deque<T> needs to do a lot more work to determine the element to access and there is also an indication. Like, iterators on std::deque<T> need to do multiple checks (although algorithms could optimize this out mostly making the overhead rather small by recognizing the segmented structure. Thus, if you need to use the subscript operator often std::deque<T> may be a bad choice and the cost of moving elements in a std::vector<T> when inserting/deleting at the front may be offset.

Just to explain, roughly what std::deque<T> needs to do in case of using a subscript operator: it can be thought of doing these operations:

T& deque<T>::operator[](size_t n) {
    n += this->first_element;
    size_t subarray = n / size_of_subarrays;
    size_t index    = n % size_of_subarrays;
    return this->subarrays[subarray][index];
}

The division/modulus operators are unlikely to be too expensive as size_of_subarray is almost certainly chosen to be a power of 2, i.e., they basically amount to bit operations.

like image 117
Dietmar Kühl Avatar answered Oct 11 '22 18:10

Dietmar Kühl