Consider I have the following:
edge some_edge;
std::priority_queue<edge> my_queue;
Is it safe to write such an ‘if’ even if the queue might be empty?
if ((my_queue.size() > 0) && (my_queue.top().weight < some_edge.weight)) {
do_something;
}
What about this one?
if ((my_queue.top().weight < some_edge.weight) && (my_queue.size() > 0)) {
do_something;
}
Does evaluating an expression in which ‘and’ is the operator between the operands stop if the left operand evaluates false?
An
ifstatement in C++ is left to right associative and the logical boolean operators&&and||are short circuiting, so yes, a statement like the following is safe because it is guaranteed that you check the size first (assuming no evil overloading of these operators):The reverse is not true however because you check the return value of
size()after popping the queue.As an aside,
std::priority_queueprovides anempty()function that I/many would prefer oversize() > 0, but that works too.