Search code examples
c++priority-queue

Printing a Priority Queue


I am attempting to print a STL priority_queue in C++, but I am having issues printing all elements of the queue.

priority_queue<Job, vector<Job>, greater<Job>> q = pq;
for(int i = 0; i <= q.size(); i++) {
    cout << q.top() << "\n";
    q.pop();
}

However, using this code when there is one or two elements in the list it is fine, but as soon as I enter three or more elements it cuts off the last item to be printed. I'm not really sure why this is happening but it's been confusing me for a little while.


Solution

  • For loops arent really meant to be used for cases when the condition is "dynamic". What I mean is: i <= q.size() is of course evaluated on every iteration, but q.size() is also changing on each iteration. It is not impossible to get the for loop right, but a while is more natural:

    while (! q.empty() ) {
        cout << q.top() << "\n";
        q.pop();
    }
    

    Your code is wrong because you increment i on every iteraton and at the same time q.size() decreases on every iteration.