28

What is the difference between std::vector and std::stack?

Obviously vectors can delete items within the collection (albeit much slower than list) whereas the stack is built to be a LIFO-only collection.

However, are stacks faster for end-item manipulation? Is it a linked list or dynamically re-allocated array?

I can't find much information about stacks, but if I'm picturing them correctly (they are similar to an actual thread stack; push, pop, etc. - along with that top() method) then they seem perfect for window-stacking management.

Qix - MONICA WAS MISTREATED
  • 14,451
  • 16
  • 82
  • 145
  • 2
    The former is a container, the latter is a container _adapter_. – ildjarn Sep 18 '12 at 23:24
  • 1
    "albeit much slower than list" Theoretically, yes. Practically, no. `vector` will outperform `list` for almost every use case. – James McNellis Sep 18 '12 at 23:24
  • @JamesMcNellis for deleting records in the middle of large vector datasets? Isn't that much slower than lists, which are double-listed? – Qix - MONICA WAS MISTREATED Sep 19 '12 at 03:22
  • Possible duplicate of [What is the major difference between a vector and a stack?](https://stackoverflow.com/questions/8785841/what-is-the-major-difference-between-a-vector-and-a-stack) – underscore_d Dec 07 '17 at 21:35

1 Answers1

58

A stack is not a container; it is a container adapter. It has a vector, deque or similar container that it stores as a member that actually holds the elements. Remember: it is declared as:

template<
    class T,
    class Container = std::deque<T>
> class stack;

All stack does is limit the user interface to this internal container. The performance characteristics of the operations are exactly whatever the underlying container's performance characteristics are.

Nicol Bolas
  • 449,505
  • 63
  • 781
  • 982
  • I think I understand what is meant by the term `container adapter`, still wondering though if there is specific definition. Is there a list of what can be called `container adapters` anywhere? – KcFnMi Jan 14 '23 at 08:03