Struct BinaryHeap
struct BinaryHeap<T, A: Allocator = crate::alloc::Global> { ... }
A priority queue implemented with a binary heap.
This will be a max-heap.
It is a logic error for an item to be modified in such a way that the
item's ordering relative to any other item, as determined by the Ord
trait, changes while it is in the heap. This is normally only possible
through interior mutability, global state, I/O, or unsafe code. The
behavior resulting from such a logic error is not specified, but will
be encapsulated to the BinaryHeap that observed the logic error and not
result in undefined behavior. This could include panics, incorrect results,
aborts, memory leaks, and non-termination.
As long as no elements change their relative order while being in the heap
as described above, the API of BinaryHeap guarantees that the heap
invariant remains intact i.e. its methods all behave as documented. For
example if a method is documented as iterating in sorted order, that's
guaranteed to work as long as elements in the heap have not changed order,
even in the presence of closures getting unwinded out of, iterators getting
leaked, and similar foolishness.
Examples
use BinaryHeap;
// Type inference lets us omit an explicit type signature (which
// would be `BinaryHeap<i32>` in this example).
let mut heap = new;
// We can use peek to look at the next item in the heap. In this case,
// there's no items in there yet so we get None.
assert_eq!;
// Let's add some scores...
heap.push;
heap.push;
heap.push;
// Now peek shows the most important item in the heap.
assert_eq!;
// We can check the length of a heap.
assert_eq!;
// We can iterate over the items in the heap, although they are returned in
// a random order.
for x in &heap
// If we instead pop these scores, they should come back in order.
assert_eq!;
assert_eq!;
assert_eq!;
assert_eq!;
// We can clear the heap of any remaining items.
heap.clear;
// The heap should now be empty.
assert!
A BinaryHeap with a known list of items can be initialized from an array:
use BinaryHeap;
let heap = from;
Min-heap
Either core::cmp::Reverse or a custom Ord implementation can be used to
make BinaryHeap a min-heap. This makes heap.pop() return the smallest
value instead of the greatest one.
use BinaryHeap;
use Reverse;
let mut heap = new;
// Wrap values in `Reverse`
heap.push;
heap.push;
heap.push;
// If we pop these scores now, they should come back in the reverse order.
assert_eq!;
assert_eq!;
assert_eq!;
assert_eq!;
Time complexity
| push | pop | peek/peek_mut |
|---|---|---|
| O(1)~ | O(log(n)) | O(1) |
The value for push is an expected cost; the method documentation gives a
more detailed analysis.
Implementations
impl<T> BinaryHeap<T>
const fn new() -> BinaryHeap<T>Creates an empty
BinaryHeapas a max-heap.Examples
Basic usage:
use BinaryHeap; let mut heap = new; heap.push;fn with_capacity(capacity: usize) -> BinaryHeap<T>Creates an empty
BinaryHeapwith at least the specified capacity.The binary heap will be able to hold at least
capacityelements without reallocating. This method is allowed to allocate for more elements thancapacity. Ifcapacityis zero, the binary heap will not allocate.Examples
Basic usage:
use BinaryHeap; let mut heap = with_capacity; heap.push;
impl<T, A: Allocator> BinaryHeap<T, A>
fn iter(self: &Self) -> Iter<'_, T>Returns an iterator visiting all values in the underlying vector, in arbitrary order.
Examples
Basic usage:
use BinaryHeap; let heap = from; // Print 1, 2, 3, 4 in arbitrary order for x in heap.iterfn into_iter_sorted(self: Self) -> IntoIterSorted<T, A>Returns an iterator which retrieves elements in heap order.
This method consumes the original heap.
Examples
Basic usage:
use BinaryHeap; let heap = from; assert_eq!;fn peek(self: &Self) -> Option<&T>Returns the greatest item in the binary heap, or
Noneif it is empty.Examples
Basic usage:
use BinaryHeap; let mut heap = new; assert_eq!; heap.push; heap.push; heap.push; assert_eq!;Time complexity
Cost is O(1) in the worst case.
fn capacity(self: &Self) -> usizeReturns the number of elements the binary heap can hold without reallocating.
Examples
Basic usage:
use BinaryHeap; let mut heap = with_capacity; assert!; heap.push;fn reserve_exact(self: &mut Self, additional: usize)Reserves the minimum capacity for at least
additionalelements more than the current length. Unlikereserve, this will not deliberately over-allocate to speculatively avoid frequent allocations. After callingreserve_exact, capacity will be greater than or equal toself.len() + additional. Does nothing if the capacity is already sufficient.Panics
Panics if the new capacity overflows
usize.Examples
Basic usage:
use BinaryHeap; let mut heap = new; heap.reserve_exact; assert!; heap.push;fn reserve(self: &mut Self, additional: usize)Reserves capacity for at least
additionalelements more than the current length. The allocator may reserve more space to speculatively avoid frequent allocations. After callingreserve, capacity will be greater than or equal toself.len() + additional. Does nothing if capacity is already sufficient.Panics
Panics if the new capacity overflows
usize.Examples
Basic usage:
use BinaryHeap; let mut heap = new; heap.reserve; assert!; heap.push;fn try_reserve_exact(self: &mut Self, additional: usize) -> Result<(), TryReserveError>Tries to reserve the minimum capacity for at least
additionalelements more than the current length. Unliketry_reserve, this will not deliberately over-allocate to speculatively avoid frequent allocations. After callingtry_reserve_exact, capacity will be greater than or equal toself.len() + additionalif it returnsOk(()). Does nothing if the capacity is already sufficient.Note that the allocator may give the collection more space than it requests. Therefore, capacity can not be relied upon to be precisely minimal. Prefer
try_reserveif future insertions are expected.Errors
If the capacity overflows, or the allocator reports a failure, then an error is returned.
Examples
use BinaryHeap; use TryReserveError; # find_max_slow.expect;fn try_reserve(self: &mut Self, additional: usize) -> Result<(), TryReserveError>Tries to reserve capacity for at least
additionalelements more than the current length. The allocator may reserve more space to speculatively avoid frequent allocations. After callingtry_reserve, capacity will be greater than or equal toself.len() + additionalif it returnsOk(()). Does nothing if capacity is already sufficient. This method preserves the contents even if an error occurs.Errors
If the capacity overflows, or the allocator reports a failure, then an error is returned.
Examples
use BinaryHeap; use TryReserveError; # find_max_slow.expect;fn shrink_to_fit(self: &mut Self)Discards as much additional capacity as possible.
Examples
Basic usage:
use BinaryHeap; let mut heap: = with_capacity; assert!; heap.shrink_to_fit; assert!;fn shrink_to(self: &mut Self, min_capacity: usize)Discards capacity with a lower bound.
The capacity will remain at least as large as both the length and the supplied value.
If the current capacity is less than the lower limit, this is a no-op.
Examples
use BinaryHeap; let mut heap: = with_capacity; assert!; heap.shrink_to; assert!;fn as_slice(self: &Self) -> &[T]Returns a slice of all values in the underlying vector, in arbitrary order.
Examples
Basic usage:
use BinaryHeap; use ; let heap = from; sink.write.unwrap;fn into_vec(self: Self) -> Vec<T, A>Consumes the
BinaryHeapand returns the underlying vector in arbitrary order.Examples
Basic usage:
use BinaryHeap; let heap = from; let vec = heap.into_vec; // Will print in some order for x in vecfn allocator(self: &Self) -> &AReturns a reference to the underlying allocator.
fn len(self: &Self) -> usizeReturns the length of the binary heap.
Examples
Basic usage:
use BinaryHeap; let heap = from; assert_eq!;fn is_empty(self: &Self) -> boolChecks if the binary heap is empty.
Examples
Basic usage:
use BinaryHeap; let mut heap = new; assert!; heap.push; heap.push; heap.push; assert!;fn drain(self: &mut Self) -> Drain<'_, T, A>Clears the binary heap, returning an iterator over the removed elements in arbitrary order. If the iterator is dropped before being fully consumed, it drops the remaining elements in arbitrary order.
The returned iterator keeps a mutable borrow on the heap to optimize its implementation.
Examples
Basic usage:
use BinaryHeap; let mut heap = from; assert!; for x in heap.drain assert!;fn clear(self: &mut Self)Drops all items from the binary heap.
Examples
Basic usage:
use BinaryHeap; let mut heap = from; assert!; heap.clear; assert!;
impl<T, A: Allocator> BinaryHeap<T, A>
const fn new_in(alloc: A) -> BinaryHeap<T, A>Creates an empty
BinaryHeapas a max-heap, usingAas allocator.Examples
Basic usage:
use System; use BinaryHeap; let mut heap = new_in; heap.push;fn with_capacity_in(capacity: usize, alloc: A) -> BinaryHeap<T, A>Creates an empty
BinaryHeapwith at least the specified capacity, usingAas allocator.The binary heap will be able to hold at least
capacityelements without reallocating. This method is allowed to allocate for more elements thancapacity. Ifcapacityis zero, the binary heap will not allocate.Examples
Basic usage:
use System; use BinaryHeap; let mut heap = with_capacity_in; heap.push;
impl<T: Ord, A: Allocator> BinaryHeap<T, A>
fn peek_mut(self: &mut Self) -> Option<PeekMut<'_, T, A>>Returns a mutable reference to the greatest item in the binary heap, or
Noneif it is empty.Note: If the
PeekMutvalue is leaked, some heap elements might get leaked along with it, but the remaining elements will remain a valid heap.Examples
Basic usage:
use BinaryHeap; let mut heap = new; assert!; heap.push; heap.push; heap.push; if let Some = heap.peek_mut assert_eq!;Time complexity
If the item is modified then the worst case time complexity is O(log(n)), otherwise it's O(1).
fn pop(self: &mut Self) -> Option<T>Removes the greatest item from the binary heap and returns it, or
Noneif it is empty.Examples
Basic usage:
use BinaryHeap; let mut heap = from; assert_eq!; assert_eq!; assert_eq!;Time complexity
The worst case cost of
popon a heap containing n elements is O(log(n)).fn push(self: &mut Self, item: T)Pushes an item onto the binary heap.
Examples
Basic usage:
use BinaryHeap; let mut heap = new; heap.push; heap.push; heap.push; assert_eq!; assert_eq!;Time complexity
The expected cost of
push, averaged over every possible ordering of the elements being pushed, and over a sufficiently large number of pushes, is O(1). This is the most meaningful cost metric when pushing elements that are not already in any sorted pattern.The time complexity degrades if elements are pushed in predominantly ascending order. In the worst case, elements are pushed in ascending sorted order and the amortized cost per push is O(log(n)) against a heap containing n elements.
The worst case cost of a single call to
pushis O(n). The worst case occurs when capacity is exhausted and needs a resize. The resize cost has been amortized in the previous figures.fn into_sorted_vec(self: Self) -> Vec<T, A>Consumes the
BinaryHeapand returns a vector in sorted (ascending) order.Examples
Basic usage:
use BinaryHeap; let mut heap = from; heap.push; heap.push; let vec = heap.into_sorted_vec; assert_eq!;fn append(self: &mut Self, other: &mut Self)Moves all the elements of
otherintoself, leavingotherempty.Examples
Basic usage:
use BinaryHeap; let mut a = from; let mut b = from; a.append; assert_eq!; assert!;fn drain_sorted(self: &mut Self) -> DrainSorted<'_, T, A>Clears the binary heap, returning an iterator over the removed elements in heap order. If the iterator is dropped before being fully consumed, it drops the remaining elements in heap order.
The returned iterator keeps a mutable borrow on the heap to optimize its implementation.
Note:
.drain_sorted()is O(n * log(n)); much slower than.drain(). You should use the latter for most cases.
Examples
Basic usage:
use BinaryHeap; let mut heap = from; assert_eq!; drop; // removes all elements in heap order assert_eq!;fn retain<F>(self: &mut Self, f: F) where F: FnMut(&T) -> boolRetains only the elements specified by the predicate.
In other words, remove all elements
efor whichf(&e)returnsfalse. The elements are visited in unsorted (and unspecified) order.Examples
Basic usage:
use BinaryHeap; let mut heap = from; heap.retain; // only keep even numbers assert_eq!
impl<'a, T: 'a + Ord + Copy, A: Allocator> Extend for BinaryHeap<T, A>
fn extend<I: IntoIterator<Item = &'a T>>(self: &mut Self, iter: I)fn extend_one(self: &mut Self, item: &'a T)fn extend_reserve(self: &mut Self, additional: usize)
impl<T> Any for BinaryHeap<T, A>
fn type_id(self: &Self) -> TypeId
impl<T> Borrow for BinaryHeap<T, A>
fn borrow(self: &Self) -> &T
impl<T> BorrowMut for BinaryHeap<T, A>
fn borrow_mut(self: &mut Self) -> &mut T
impl<T> CloneToUninit for BinaryHeap<T, A>
unsafe fn clone_to_uninit(self: &Self, dest: *mut u8)
impl<T> Default for BinaryHeap<T>
fn default() -> BinaryHeap<T>Creates an empty
BinaryHeap<T>.
impl<T> From for BinaryHeap<T, A>
fn from(t: T) -> TReturns the argument unchanged.
impl<T> ToOwned for BinaryHeap<T, A>
fn to_owned(self: &Self) -> Tfn clone_into(self: &Self, target: &mut T)
impl<T, A> Freeze for BinaryHeap<T, A>
impl<T, A> RefUnwindSafe for BinaryHeap<T, A>
impl<T, A> Send for BinaryHeap<T, A>
impl<T, A> Sync for BinaryHeap<T, A>
impl<T, A> Unpin for BinaryHeap<T, A>
impl<T, A> UnwindSafe for BinaryHeap<T, A>
impl<T, A: Allocator> IntoIterator for BinaryHeap<T, A>
fn into_iter(self: Self) -> IntoIter<T, A>Creates a consuming iterator, that is, one that moves each value out of the binary heap in arbitrary order. The binary heap cannot be used after calling this.
Examples
Basic usage:
use BinaryHeap; let heap = from; // Print 1, 2, 3, 4 in arbitrary order for x in heap.into_iter
impl<T, U> Into for BinaryHeap<T, A>
fn into(self: Self) -> UCalls
U::from(self).That is, this conversion is whatever the implementation of
[From]<T> for Uchooses to do.
impl<T, U> TryFrom for BinaryHeap<T, A>
fn try_from(value: U) -> Result<T, <T as TryFrom<U>>::Error>
impl<T, U> TryInto for BinaryHeap<T, A>
fn try_into(self: Self) -> Result<U, <U as TryFrom<T>>::Error>
impl<T: Clone, A: Allocator + Clone> Clone for BinaryHeap<T, A>
fn clone(self: &Self) -> Selffn clone_from(self: &mut Self, source: &Self)Overwrites the contents of
selfwith a clone of the contents ofsource.This method is preferred over simply assigning
source.clone()toself, as it avoids reallocation if possible.See [
Vec::clone_from()] for more details.
impl<T: Ord> FromIterator for BinaryHeap<T>
fn from_iter<I: IntoIterator<Item = T>>(iter: I) -> BinaryHeap<T>
impl<T: Ord, A: Allocator> Extend for BinaryHeap<T, A>
fn extend<I: IntoIterator<Item = T>>(self: &mut Self, iter: I)fn extend_one(self: &mut Self, item: T)fn extend_reserve(self: &mut Self, additional: usize)
impl<T: Ord, A: Allocator> From for BinaryHeap<T, A>
fn from(vec: Vec<T, A>) -> BinaryHeap<T, A>Converts a
Vec<T>into aBinaryHeap<T>.This conversion happens in-place, and has O(n) time complexity.
impl<T: Ord, N: usize> From for BinaryHeap<T>
fn from(arr: [T; N]) -> Selfuse BinaryHeap; let mut h1 = from; let mut h2: = .into; while let Some = h1.pop.zip
impl<T: fmt::Debug, A: Allocator> Debug for BinaryHeap<T, A>
fn fmt(self: &Self, f: &mut fmt::Formatter<'_>) -> fmt::Result