Domanda

I was going over this post and it states that deque provides efficent insetion at the top and bottom.However this post here states that time complexity of deque other than the back is O(n).I would think that if a deque has efficent top and bottom insertion it would have O(1) while a vector should have O(1) at bottom insertion only. I would appreciate it if someone could clarify this

È stato utile?

Soluzione 3

The cppreference entry for std::deque gives the following complexity:

The complexity (efficiency) of common operations on deques is as follows:

  • Random access - constant O(1)
  • Insertion or removal of elements at the end or beginning - amortized constant O(1)
  • Insertion or removal of elements - linear O(n)

which is consistent with the draft C++ standard section 23.3.3.1 Class template deque overview which says (emphasis mine):

A deque is a sequence container that, like a vector (23.3.6), supports random access iterators. In addition, it supports constant time insert and erase operations at the beginning or the end; insert and erase in the middle take linear time. That is, a deque is especially optimized for pushing and popping elements at the beginning and end. As with vectors, storage management is handled automatically.

For std::vector cppreference says:

The complexity (efficiency) of common operations on vectors is as follows:

  • Random access - constant O(1)
  • Insertion or removal of elements at the end - amortized constant O(1)
  • Insertion or removal of elements - linear in distance to the end of the vector O(n)

which is consistent with the draft standard section 23.3.6.1 Class template vector overview:

A vector is a sequence container that supports random access iterators. In addition, it supports (amortized) constant time insert and erase operations at the end; insert and erase in the middle take linear time. Storage management is handled automatically, though hints can be given to improve efficiency.[...]

Altri suggerimenti

C++98, section 23.2.1 (Template class deque)

"A deque ... supports constant time insert and erase operations at the beginning or the end; insert and erase in the mid-dle take linear time. That is, a deque is especially optimized for pushing and popping elements at the beginning and end. As with vectors, storage management is handled automatically."

So yes: O(1) insertion at both ends.

From the C++ standard:

23.3.3.4 deque modifiers [deque.modifiers]

[...]
void push_front(const T& x);
void push_front(T&& x);
void push_back(const T& x);
void push_back(T&& x);

[...]

3 Complexity: The complexity is linear in the number of elements inserted plus the lesser of the distances to the beginning and end of the deque. Inserting a single element either at the beginning or end of a deque always takes constant time and causes a single call to a constructor of T.

Emphasis mine

Autorizzato sotto: CC-BY-SA insieme a attribuzione
Non affiliato a StackOverflow
scroll top