sekineh/binary-heap-plus-rs

How to collect from iterator with `MinComparator` ?

Stargateur opened this issue · 2 comments

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 ?

I think you need to modify the signature below

// #[stable(feature = "rust1", since = "1.0.0")]
impl<T: Ord> FromIterator<T> for BinaryHeap<T> {

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.

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.