0

Say I have the following struct:

struct Node {
    location: Location,
    price: f32
}

And now, I want to store a number of Nodes in a BinaryHeap.

let heap: BinaryHeap<Node> = BinaryHeap::new(); 

However, since I have not implemented Ord for Node, the above declaration would err.

Problem

There are at least two ways to implement the cmp function for Node:

// compare by price
fn cmp(&self, other: &Self) -> Ordering {
        other.price.cmp(&self.price)
}

// or compare by distance (not sure if I can add an extra argument, but let's assume we can)
fn cmp(&self, other: &Self, source_node: &Node) -> Ordering {
        other.distance_to(source_node).cmp(&self.distance_to(source_node))
}

And I want to give user the ability to pass in their own custom cmp function, and use that for BinaryHeap ordering.

In Java, you can pass in a custom comparator function for PriorityQueue: see here for an example. But it seems like BinaryHeap in rust doesn't really have that ability.

Are there any workarounds to achieve this?

PipEvangelist
  • 601
  • 1
  • 7
  • 22
  • 1
    Well, you specify the comparator by `impl`ing `Ord` for the type you use. You can create a wrapper type if you want: a tuple struct that holds a Node in its `0` field and a custom `Ord` implementation will do. – FZs Aug 27 '22 at 22:04
  • This may be far too late to be of any use to you @PipEvangelist, but for future readers of this question it may be helpful to know that my (recently published) [copse](https://crates.io/crates/copse) crate provides an alternative `BinaryHeap` that can be instantiated with a custom/runtime-defined comparator (or at least it will, once v0.3.0 is released: the currently published versions only provide a `BTreeMap` and `BTreeSet`, but you can use the master branch from [github repo](https://github.com/eggyal/copse) in the interim). – eggyal Jan 16 '23 at 19:58

0 Answers0