C++11.
If I try to pop off of an empty priority_queue, then I get a compile time error. Specifically,
#include <iostream>
#include <queue>
int main()
{
std::priority_queue<int> pq;
int x = pq.pop();
std::cout << x << std::endl;
}
yields the compile-time error:
In function 'int main()': 7:20: error: void value not ignored as it ought to be
I am surprised that this is a compile-time error and not a runtime error, but that is another discussion.
What I don't understand is why the top method wouldn't do the same thing. In fact, if we change pop to top the code actually compiles and runs (albeit with a bizzare output). Specifically,
#include <iostream>
#include <queue>
int main()
{
std::priority_queue<int> pq;
int x = pq.top();
std::cout << x << std::endl;
}
This code compiles, runs, and exits normally, but produces no output! It literally prints nothing. I do not understand how that can be.
Here are my questions:
Is the behavior for
popandtopdefined if thepriority_queueis empty? I don't see any mention of this condition in the docs.How is there no output in the second case?
topreturns a constant reference. So it must be pointing at something. I would imagine that it simply interprets whatever piece of memory it is pointing to as an integer. But that doesn't seem to be happening. It seems like the integer is behaving something like anullptr.