Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Why does C++ standard queue have back function when stack doesn't have bottom function?

Tags:

c++

stack

std

queue

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.

like image 845
whiteSkar Avatar asked Feb 01 '14 22:02

whiteSkar


People also ask

Why does stack :: top return a reference?

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.

Does queue pop return value?

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.

Does pop return a value in stack?

pop() removes element from stack and returns nothing.

Does stack POP return a value C++?

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.


2 Answers

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 swapping 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.

like image 72
Steve Jessop Avatar answered Sep 20 '22 10:09

Steve Jessop


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.

like image 26
Lie Ryan Avatar answered Sep 22 '22 10:09

Lie Ryan