Meysam
Meysam

Reputation: 18137

Why is the size of an empty queue reduced by one after pop?

#include <queue>
#include <stdio.h>

int main ()
{
    std::queue<int> q;
    printf("%d\n", q.size());

    q.pop();
    q.pop();

    printf("%d\n", q.size());  // ===> prints -2

    return 0;
}

Upvotes: 0

Views: 1208

Answers (3)

Mike Vine
Mike Vine

Reputation: 9837

It is undefined behaviour to pop from an empty queue.

Undefined behavoir can include many things such as formatting your harddrive (unlikely!), making demons appear from your nose (also unlikely) or sometimes doing exactly what you expect (likely and very worrying)

You're also printing a size_t using %d which will only lead to trouble. Try using %zu (on gcc/clang) or %Iu on Visual Studio

Upvotes: 2

taocp
taocp

Reputation: 23634

According to Unexpected behavior from STL's queue with a little tweak.

std::queue is a very thin adaptor (i.e. wrapper) around another container, the behaviour you are reporting is actually the behaviour of std::deque, not std::queue since you don't change the default container.

calling pop() on an empty sequence is undefined behaviour.

Upvotes: 2

nos
nos

Reputation: 229108

Calling queue.pop() on an empty container yields undefined behavior, so you cannot really rely on anything about your program after you've done this.

Having your queue potentially damaged and report a size() of -1 is correct/good/bad as anything when you've invoked undefined behavior.

Upvotes: 3

Related Questions