4

Like the title asks Is there any time or space difference between a std::vector used as a stack and a std::stack ?

user2370139
  • 1,297
  • 1
  • 11
  • 13

2 Answers2

4

A std::stack wraps another container. If the backing container of your stack is a std::vector, then no, there is no difference.

The default backing container is however a std::deque, which can have different storage and timing behaviour

See std::stack for details

king_nak
  • 11,313
  • 33
  • 58
3

No, there is no difference in complexity. std::vector is a Container. std::stack is an Adaptor of a container.

By default std::stack uses std::deque as the container it "adapts". But its actually a class-template that allows you to pass in the type of the underlying container you want it to use.


You can equally use a std::vector as the underlying container:

template<typename T>
using MyVectorStack = std::stack<T, std::vector<T>>;


However,

In the case of std::stack, the difference between using std::deque vs std::vector as the underlying container is primarily its memory allocation strategies.

When popping from a std::vector, there's no chance that memory will be returned to the memory allocator unless if the vector is empty. When popping from a std::deque, memory may be returned to the memory allocator if the "pop" frees a deque block.

See Why does std::stack use std::deque by default?

Community
  • 1
  • 1
WhiZTiM
  • 21,207
  • 4
  • 43
  • 68