sekineh / binary-heap-plus-rs

Enhancement over Rust's `std::collections::BinaryHeap`. Supports other than max heap.
MIT License
57 stars 18 forks source link

Add BinaryHeap::replace_cmp() and unsafe version BinaryHeap::replace_cmp_raw() #26

Closed davidli2010 closed 4 years ago

davidli2010 commented 4 years ago

Add BinaryHeap::replace_cmp() and its unsafe version BinaryHeap::replace_cmp_raw() to replace the comparator at runtime.

The two functions are similar with #22 and can be used when we only have a mutable reference to BinaryHeap.

For example:

use binary_heap_plus::*;
use compare::Compare;
use std::cmp::Ordering;

struct Comparator {
    ascending: bool
}

impl Compare<i32> for Comparator {
    fn compare(&self,l: &i32,r: &i32) -> Ordering {
        if self.ascending {
            r.cmp(l)
        } else {
            l.cmp(r)
        }
    }
}

// construct a heap in ascending order.
let mut heap = BinaryHeap::from_vec_cmp(vec![3, 1, 5], Comparator { ascending: true });

// replace the comparor
heap.replace_cmp(Comparator { ascending: false });
assert_eq!(heap.into_iter_sorted().collect::<Vec<_>>(), vec![5, 3, 1]);
sekineh commented 4 years ago

Do you have any other PR#s to be sent? If no, I'm going to prepare the new release of this crate. (v0.3.1)

davidli2010 commented 4 years ago

Do you have any other PR#s to be sent? If no, I'm going to prepare the new release of this crate. (v0.3.1)

No, thanks. I'm looking forward to a new version, so that I can use it in my project :-)

sekineh commented 4 years ago

I've just published v0.3.1!