Both act like a stack. Both have push and pop operations.
Is the difference in some memory layouts?
Practically, no. vector will outperform list for almost every use case.
A stack is a type of linear data structure that is represented by a collection of pieces that are arranged in a predetermined sequence. An array is a collection of data values that are associated to one another and termed elements.
Stack behavior with std::vector Although std::vector can be used as a dynamic array, it can also be used as a stack. To do this, we can use 3 functions that match our key stack operations: push_back() pushes an element on the stack.
std::vector
has several accessibility and modification operations compared to std::stack
. In case of std::stack
, you may have to perform operations only in systematic way, where you can push()
above the last element or pop()
the last element.
std::vector
is more flexible in that sense, where it has several operations, where you can insert()
in between or erase()
in between.
The major point is that, std::stack needs to be provided the underlying container. By default it's std::deque
, but it can be std::vector
or std::list
too.
On other hand, std::vector
is guaranteed to be a contiguous array which can be accessed using operator []
.
I'm not aware of all the implementation details, but according to this, stack is a container adaptor. It makes sure the underlying container, which can be a vector, list or deque, works as a stack, i.e. only allows push and pop, and not random access.
So, a vector can work as a stack, but a stack cannot work as a vector, because you cannot insert or get an element at a random position.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With