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

with_capacity_by is not expected #9

Closed xingzhicn closed 5 years ago

xingzhicn commented 5 years ago

I want to create a Binary Heap of fixed length,but the length is not expected.

    // custom-sort heap
    let mut heap1 = BinaryHeap::with_capacity_by(2,|a: &(i32,i32), b: &(i32,i32)| b.1.cmp(&a.1));
    heap1.push((1,5));
    heap1.push((3,2));
    heap1.push((2,1));
    heap1.push((1,1));
    heap1.push((1,0));
    assert_eq!(heap1.pop(), Some((1,0))); // min value
    assert_eq!(heap1.pop(), Some((2,1))); // min value
    assert_eq!(heap1.pop(), Some((1,1))); // min value
    assert_eq!(heap1.pop(), Some((3,2))); // min value
sekineh commented 5 years ago

Hi,

BinaryHeap::with_capacity_by() does not limit the actual length of the heap. It behaves exactly like Vec::with_capacity() which allocate the capacity beforehand to avoid later reallocation.

For more explanation, please read the docs below:

If you want to limit the actual length of any BinaryHeap or Vec, you need to check .len() before pushing element onto it. I believe you can write a thin wrapper that perform this operation automatically.