kyle newton
kyle newton

Reputation: 81

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.

Upvotes: 4

Views: 11175

Answers (2)

463035818_is_not_an_ai
463035818_is_not_an_ai

Reputation: 122133

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.

Upvotes: 12

Nishant Singh
Nishant Singh

Reputation: 4855

since you are changing the size of priority queue in the loop, the code is not running correct. Try following code :

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

Upvotes: 1

Related Questions