Why would I use a std::stack
or a std::queue
rather than a std::vector
or a std::deque
?
Since the container adapters are merely wrappers around the standard containers, why use them at all?
Why would I use a std::stack
or a std::queue
rather than a std::vector
or a std::deque
?
Since the container adapters are merely wrappers around the standard containers, why use them at all?
To limit the user interface
You don't want your stack to be able to remove elements somewhere else instead of top. Why to use vector in place of stack if you have exactly same performance also stack improves readability and reliability.
std::stack
is more expressive than std::vector
when the container you want to implement is truly a LIFO
.
For convenience. They provide a semantic API tailored to the needs.
Readability. stack.top()
looks better than stack[0]
, or stack[stack.size()]
*, or stack.back()
. Reader of such code does not need to interpret meaning of such a construct. It is given.
*Note: As @moooeeeep suggest it should be size()-1
if anything, but I am leaving original as a nice example why one should use supplied solutions instead of writing even most simple things by hand.
std::stack
is an adapter for containers (could be of a vector, a list of whatsnut container). The main purpose is to transform the interface of the underlying container into that one of a stack. Such giving you push()
, top()
and pop()
instead of push_back()
, back()
and pop_back()
.
Queue and deque follow the same scheme. A queue is a deque with less operations possible.