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

How to collect from iterator with `MinComparator` ? #2

Closed Stargateur closed 5 years ago

Stargateur commented 5 years ago

I tried: let _ : BinaryHeap<_, MinComparator> = (0..42).collect();, but this doesn't work cause the trait

std::iter::FromIterator<{integer}> is not implemented for binary_heap_plus::binary_heap::BinaryHeap<_, binary_heap_plus::binary_heap::MinComparator>

Is it possible to add this feature ?

sekineh commented 5 years ago

I think you need to modify the signature below

https://github.com/sekineh/binary-heap-plus-rs/blob/570650514cb8cee5dfbb84efbb688722c09916b0/src/binary_heap.rs#L1337-L1338

to like this:

impl<T, C: Compare<T>> FromIterator<T> for BinaryHeap<T, C> {

I'm not sure if it is 100% backward-compatible though.

sekineh commented 5 years ago

The reason why I can't add this feature

The problem is that if I added the following implementation,

impl<T, C: Compare<T>> FromIterator<T> for BinaryHeap<T, C> {

existing code would break and need to add some type annotation.

So I don't add this impl for the time being. If clever people might know better way, please send us a PR.

Suggestion

By the way, given that BinaryHeap's internal representation is just a Vec<>, constructing from a vector is quite natural.

Why don't you write like this instead?

    // let _ : BinaryHeap<_, MinComparator> = (0..42).collect();
    let mut h: BinaryHeap<_, MinComparator> = BinaryHeap::from_vec((0..42).collect());
    assert_eq!(h.pop(), Some(0));

I confirmed it compiles and runs fine.