On one of many unofficial C++ reference websites, there are listed member functions front()
and back()
for std::queue
. However, std::stack
only has top()
function.
It makes sense for the stack to not have a bottom()
function because that's the definition of a stack.
What I don't get is why did the C++ standard committee chose not to follow the definition of a queue and provide with back()
function for queue and chose to follow the definition of a stack and not provide with bottom()
function.
std::stack::top Returns a reference to the top element in the stack . Since stacks are last-in first-out containers, the top element is the last element inserted into the stack. This member function effectively calls member back of the underlying container object.
Since it is impossible for pop() to return a value in such a way as to be both efficient and correct, it is more sensible for it to return no value at all and to require clients to use front() to inspect the value at the front of the queue.
pop() removes element from stack and returns nothing.
The function is used only for the removal of elements from the stack and has no return value. Hence we can say that the return type of the function is void.
There might be other reasons for back()
, but you needed it for a queue because of the idiom from C++03 of cheaply copying an "empty" object into a container and then swap
ping that new element with a "full" object that would be very expensive to copy. This reason is more or less obsolete in C++11 thanks to move semantics, but of course back()
is still needed for compatibility.
You don't need bottom()
for a stack for that (or any other) reason.
It actually makes sense in a weird way. In a queue, you push on one side and pop from the other so both sides are very likely to change a lot. With a stack, you push and pop both from the top, and the bottom of the stack very rarely changes. So, it's rarely interesting to query the current value of the bottom of a stack.
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