queue.back() always has some value even after popping all elements of queue why?

your textwhen i traverse through queue and print elements, after the traversal size of queue is zero, but queue.back() is printing the last value, can you help me.

Code

s.back() should print zero but it is printing 30.

>Solution :

A C++ program that compiles and seems to run is not necessarily a correct program. ‘std::queue’ by default is an adapter for std::deque.

Reading documentation is a skill you should develop too and cppreference is the place to look things up. So read the documentation on deque’s back method : https://en.cppreference.com/w/cpp/container/deque/back

The undefined behavior means, the call has no meaning when the queue is empty and that it will leave your program in an undefined state. The bad thing is that things may seem to work, but you can no longer trust your program to do the right things after you made such a call.

Leave a Reply