I'd like to have a container of points that are sorted by the distance to some point, which is given at runtime. In other languages, I could supply the container with a custom compare function, however, I understand this is not possible in rust.
Consider the following code problem:
/// distance between two points
fn distance(a: &(f32, f32), b: &(f32, f32)) -> f32 {
((a.0-b.0)*(a.0-b.0) + (a.1-b.1)*(a.1-b.1)).sqrt()
}
fn main() {
let origin = (1, 1); // assume values are provided at runtime
let mut container = BTreeSet::new(); // should be sorted by distance to origin
container.insert((1 ,9));
container.insert((2 ,2));
container.insert((1 ,5));
}
After the insertions I want the container to be sorted as [(2,2),(1,5),(1,9)]
. The example uses BTreeSet
, which I don't insist on using, but it feels like the closest to what I need.
I do NOT want a Vec
that I have to resort manually after every insert()
.
So how do I connect distance()
, origin
, and container
, preferably without third-party dependencies?