priority-queue icon indicating copy to clipboard operation
priority-queue copied to clipboard

No way to iterate without consuming the queue?

Open fabiensanglard opened this issue 3 months ago • 1 comments

Is it a conscious design decision to not allow user to iterate over a queue without consuming it?

use priority_queue::PriorityQueue;

let mut pq = PriorityQueue::new();

assert!(pq.is_empty());
pq.push("Apples", 5);

for (item, _) in pq.into_sorted_iter() {
    println!("{}", item); // Will print Bananas, Strawberries, Apples
}

pq.change_priority("Bananas", 25); // ERROR

Why not have a sorted_iter method?

fabiensanglard avatar Oct 20 '25 03:10 fabiensanglard

The reason is that, in general, the queue is never completely sorted.

Every time the top element is poped, the queue structure is restored such that the next pop can quickly extract the new top element. This is not a complete sorting, but it applies the heap algorithm.

A method to extract the elements in order while a certain condition is true is in the work, but I did not have time to finish it yet. This method would allow to have the queue back (without the extracted elements) when the iterator goes out of scope.

I am open to accept working implementations of a sorted_iter method that maintains (or restores when finished) the queue structure. Notice though that probably it would need to take a &mut self kind of reference to be able to change the position of elements inside the heap.

garro95 avatar Nov 11 '25 06:11 garro95