0

I first push into the stack and then pop from it. From the empty stack I cout stack.top() and it prints the element which I have pushed earlier. Why is it so??

        priority_queue<int, vector<int>, greater<int>>minHeap ;

        minHeap.push(1) ;
        minHeap.pop() ;
        cout << minHeap.top() ;

Why the output of this is 1??

AKA_RAN
  • 1
  • 1
  • Does this answer your question? [C++ Behavior of priority\_queue pop() and top() when queue is empty](https://stackoverflow.com/questions/54368314/c-behavior-of-priority-queue-pop-and-top-when-queue-is-empty) – Raymond Chen Mar 16 '23 at 05:02

1 Answers1

0

If I understand you code correctly you are pushingg 1 to the stack and then popping it leaving the stack empty. I suspect the pop function isn't clearing the element when the last item is deleted.

There is probably some function to see if the stack is empty which you should call before you print top.

Code Gorilla
  • 962
  • 9
  • 23