Iter_mut() for BinaryHeap?


#1

I’m using a BinaryHeap to implement an event-driven simulation. Each element of the heap contains a “priority” (OrderedFloat<f64>), which determines the ordering of the elements, and some associated data. I would like to be able to iterate through the heap (the order of iteration doesn’t matter) and modify the data without touching the priority.

Presently, BinaryHeap does not have an iter_mut() function, presumably because modifying the priority would mess up the element ordering. Since I don’t care to modify the priorities, this isn’t an issue for me.

Is there a way to add iter_mut() to BinaryHeap?


#2

This is probably best achieved using interior mutability.

struct HeapElement {
  priority: OrderedFloat<f64>,
  data: RefCell<HeapElementData>
}

struct HeapElementData {
  // ...
}

You can then use iter and call elem.data.borrow_mut() to modify each item.


#3

Thanks, I think your suggestion will work.