Type Definition dary_heap::QuaternaryHeap
source · pub type QuaternaryHeap<T> = DaryHeap<T, 4>;
Expand description
A quaternary heap (d = 4).
Implementations§
source§impl<T: Ord, const D: usize> DaryHeap<T, D>
impl<T: Ord, const D: usize> DaryHeap<T, D>
sourcepub fn new() -> DaryHeap<T, D>
pub fn new() -> DaryHeap<T, D>
Creates an empty DaryHeap
as a max-heap.
Examples
Basic usage:
use dary_heap::QuaternaryHeap;
let mut heap = QuaternaryHeap::new();
heap.push(4);
sourcepub fn with_capacity(capacity: usize) -> DaryHeap<T, D>
pub fn with_capacity(capacity: usize) -> DaryHeap<T, D>
Creates an empty DaryHeap
with at least the specific capacity.
The d-ary heap will be able to hold at least capacity
elements without
reallocating. This method is allowed to allocate for more elements than
capacity
. If capacity
is 0, the d-ary heap will not allocate.
Examples
Basic usage:
use dary_heap::QuaternaryHeap;
let mut heap = QuaternaryHeap::with_capacity(10);
heap.push(4);
sourcepub fn peek_mut(&mut self) -> Option<PeekMut<'_, T, D>>
pub fn peek_mut(&mut self) -> Option<PeekMut<'_, T, D>>
Returns a mutable reference to the greatest item in the d-ary heap, or
None
if it is empty.
Note: If the PeekMut
value is leaked, some heap elements might get
leaked along with it, but the remaining elements will remain a valid
heap.
Examples
Basic usage:
use dary_heap::TernaryHeap;
let mut heap = TernaryHeap::new();
assert!(heap.peek_mut().is_none());
heap.push(1);
heap.push(5);
heap.push(2);
{
let mut val = heap.peek_mut().unwrap();
*val = 0;
}
assert_eq!(heap.peek(), Some(&2));
Time complexity
If the item is modified then the worst case time complexity is O(log(n)), otherwise it’s O(1).
sourcepub fn pop(&mut self) -> Option<T>
pub fn pop(&mut self) -> Option<T>
Removes the greatest item from the d-ary heap and returns it, or None
if it
is empty.
Examples
Basic usage:
use dary_heap::BinaryHeap;
let mut heap = BinaryHeap::from([1, 3]);
assert_eq!(heap.pop(), Some(3));
assert_eq!(heap.pop(), Some(1));
assert_eq!(heap.pop(), None);
Time complexity
The worst case cost of pop
on a heap containing n elements is O(log(n)).
sourcepub fn push(&mut self, item: T)
pub fn push(&mut self, item: T)
Pushes an item onto the d-ary heap.
Examples
Basic usage:
use dary_heap::QuaternaryHeap;
let mut heap = QuaternaryHeap::new();
heap.push(3);
heap.push(5);
heap.push(1);
assert_eq!(heap.len(), 3);
assert_eq!(heap.peek(), Some(&5));
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 push
is O(n). The worst case
occurs when capacity is exhausted and needs a resize. The resize cost
has been amortized in the previous figures.
sourcepub fn into_sorted_vec(self) -> Vec<T>
pub fn into_sorted_vec(self) -> Vec<T>
Consumes the DaryHeap
and returns a vector in sorted
(ascending) order.
Examples
Basic usage:
use dary_heap::OctonaryHeap;
let mut heap = OctonaryHeap::from([1, 2, 4, 5, 7]);
heap.push(6);
heap.push(3);
let vec = heap.into_sorted_vec();
assert_eq!(vec, [1, 2, 3, 4, 5, 6, 7]);
sourcepub fn append(&mut self, other: &mut Self)
pub fn append(&mut self, other: &mut Self)
Moves all the elements of other
into self
, leaving other
empty.
Examples
Basic usage:
use dary_heap::OctonaryHeap;
let mut a = OctonaryHeap::from([-10, 1, 2, 3, 3]);
let mut b = OctonaryHeap::from([-20, 5, 43]);
a.append(&mut b);
assert_eq!(a.into_sorted_vec(), [-20, -10, 1, 2, 3, 3, 5, 43]);
assert!(b.is_empty());
sourcepub fn drain_sorted(&mut self) -> DrainSorted<'_, T, D> ⓘ
Available on crate feature unstable
only.
pub fn drain_sorted(&mut self) -> DrainSorted<'_, T, D> ⓘ
unstable
only.Clears the d-ary 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 dary_heap::TernaryHeap;
let mut heap = TernaryHeap::from([1, 2, 3, 4, 5]);
assert_eq!(heap.len(), 5);
drop(heap.drain_sorted()); // removes all elements in heap order
assert_eq!(heap.len(), 0);
sourcepub fn retain<F>(&mut self, f: F)where
F: FnMut(&T) -> bool,
pub fn retain<F>(&mut self, f: F)where F: FnMut(&T) -> bool,
Retains only the elements specified by the predicate.
In other words, remove all elements e
for which f(&e)
returns
false
. The elements are visited in unsorted (and unspecified) order.
Examples
Basic usage:
use dary_heap::OctonaryHeap;
let mut heap = OctonaryHeap::from([-10, -5, 1, 2, 4, 13]);
heap.retain(|x| x % 2 == 0); // only keep even numbers
assert_eq!(heap.into_sorted_vec(), [-10, 2, 4])
source§impl<T, const D: usize> DaryHeap<T, D>
impl<T, const D: usize> DaryHeap<T, D>
sourcepub fn iter(&self) -> Iter<'_, T> ⓘ
pub fn iter(&self) -> Iter<'_, T> ⓘ
Returns an iterator visiting all values in the underlying vector, in arbitrary order.
Examples
Basic usage:
use dary_heap::TernaryHeap;
let heap = TernaryHeap::from([1, 2, 3, 4]);
// Print 1, 2, 3, 4 in arbitrary order
for x in heap.iter() {
println!("{x}");
}
sourcepub fn into_iter_sorted(self) -> IntoIterSorted<T, D> ⓘ
Available on crate feature unstable
only.
pub fn into_iter_sorted(self) -> IntoIterSorted<T, D> ⓘ
unstable
only.Returns an iterator which retrieves elements in heap order. This method consumes the original heap.
Examples
Basic usage:
use dary_heap::QuaternaryHeap;
let heap = QuaternaryHeap::from([1, 2, 3, 4, 5]);
assert_eq!(heap.into_iter_sorted().take(2).collect::<Vec<_>>(), [5, 4]);
sourcepub fn peek(&self) -> Option<&T>
pub fn peek(&self) -> Option<&T>
Returns the greatest item in the d-ary heap, or None
if it is empty.
Examples
Basic usage:
use dary_heap::BinaryHeap;
let mut heap = BinaryHeap::new();
assert_eq!(heap.peek(), None);
heap.push(1);
heap.push(5);
heap.push(2);
assert_eq!(heap.peek(), Some(&5));
Time complexity
Cost is O(1) in the worst case.
sourcepub fn capacity(&self) -> usize
pub fn capacity(&self) -> usize
Returns the number of elements the d-ary heap can hold without reallocating.
Examples
Basic usage:
use dary_heap::OctonaryHeap;
let mut heap = OctonaryHeap::with_capacity(100);
assert!(heap.capacity() >= 100);
heap.push(4);
sourcepub fn reserve_exact(&mut self, additional: usize)
pub fn reserve_exact(&mut self, additional: usize)
Reserves the minimum capacity for at least additional
elements more than
the current length. Unlike reserve
, this will not
deliberately over-allocate to speculatively avoid frequent allocations.
After calling reserve_exact
, capacity will be greater than or equal to
self.len() + additional
. Does nothing if the capacity is already
sufficient.
Panics
Panics if the new capacity overflows usize
.
Examples
Basic usage:
use dary_heap::OctonaryHeap;
let mut heap = OctonaryHeap::new();
heap.reserve_exact(100);
assert!(heap.capacity() >= 100);
heap.push(4);
sourcepub fn reserve(&mut self, additional: usize)
pub fn reserve(&mut self, additional: usize)
Reserves capacity for at least additional
elements more than the
current length. The allocator may reserve more space to speculatively
avoid frequent allocations. After calling reserve
,
capacity will be greater than or equal to self.len() + additional
.
Does nothing if capacity is already sufficient.
Panics
Panics if the new capacity overflows usize
.
Examples
Basic usage:
use dary_heap::BinaryHeap;
let mut heap = BinaryHeap::new();
heap.reserve(100);
assert!(heap.capacity() >= 100);
heap.push(4);
sourcepub fn try_reserve_exact(
&mut self,
additional: usize
) -> Result<(), TryReserveError>
Available on crate feature extra
only.
pub fn try_reserve_exact( &mut self, additional: usize ) -> Result<(), TryReserveError>
extra
only.Tries to reserve the minimum capacity for at least additional
elements
more than the current length. Unlike try_reserve
, this will not
deliberately over-allocate to speculatively avoid frequent allocations.
After calling try_reserve_exact
, capacity will be greater than or
equal to self.len() + additional
if it returns Ok(())
.
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_reserve
if future insertions are expected.
Errors
If the capacity overflows, or the allocator reports a failure, then an error is returned.
Examples
use dary_heap::BinaryHeap;
use std::collections::TryReserveError;
fn find_max_slow(data: &[u32]) -> Result<Option<u32>, TryReserveError> {
let mut heap = BinaryHeap::new();
// Pre-reserve the memory, exiting if we can't
heap.try_reserve_exact(data.len())?;
// Now we know this can't OOM in the middle of our complex work
heap.extend(data.iter());
Ok(heap.pop())
}
sourcepub fn try_reserve(&mut self, additional: usize) -> Result<(), TryReserveError>
Available on crate feature extra
only.
pub fn try_reserve(&mut self, additional: usize) -> Result<(), TryReserveError>
extra
only.Tries to reserve capacity for at least additional
elements more than the
current length. The allocator may reserve more space to speculatively
avoid frequent allocations. After calling try_reserve
, capacity will be
greater than or equal to self.len() + additional
if it returns
Ok(())
. 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 dary_heap::QuaternaryHeap;
use std::collections::TryReserveError;
fn find_max_slow(data: &[u32]) -> Result<Option<u32>, TryReserveError> {
let mut heap = QuaternaryHeap::new();
// Pre-reserve the memory, exiting if we can't
heap.try_reserve(data.len())?;
// Now we know this can't OOM in the middle of our complex work
heap.extend(data.iter());
Ok(heap.pop())
}
sourcepub fn shrink_to_fit(&mut self)
pub fn shrink_to_fit(&mut self)
Discards as much additional capacity as possible.
Examples
Basic usage:
use dary_heap::TernaryHeap;
let mut heap: TernaryHeap<i32> = TernaryHeap::with_capacity(100);
assert!(heap.capacity() >= 100);
heap.shrink_to_fit();
assert!(heap.capacity() == 0);
sourcepub fn shrink_to(&mut self, min_capacity: usize)
Available on crate feature extra
only.
pub fn shrink_to(&mut self, min_capacity: usize)
extra
only.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 dary_heap::TernaryHeap;
let mut heap: TernaryHeap<i32> = TernaryHeap::with_capacity(100);
assert!(heap.capacity() >= 100);
heap.shrink_to(10);
assert!(heap.capacity() >= 10);
sourcepub fn as_slice(&self) -> &[T]
Available on crate feature unstable
only.
pub fn as_slice(&self) -> &[T]
unstable
only.Returns a slice of all values in the underlying vector, in arbitrary order.
Examples
Basic usage:
use dary_heap::OctonaryHeap;
use std::io::{self, Write};
let heap = OctonaryHeap::from([1, 2, 3, 4, 5, 6, 7]);
io::sink().write(heap.as_slice()).unwrap();
sourcepub fn into_vec(self) -> Vec<T>
pub fn into_vec(self) -> Vec<T>
Consumes the DaryHeap
and returns the underlying vector
in arbitrary order.
Examples
Basic usage:
use dary_heap::QuaternaryHeap;
let heap = QuaternaryHeap::from([1, 2, 3, 4, 5, 6, 7]);
let vec = heap.into_vec();
// Will print in some order
for x in vec {
println!("{x}");
}
sourcepub fn len(&self) -> usize
pub fn len(&self) -> usize
Returns the length of the d-ary heap.
Examples
Basic usage:
use dary_heap::BinaryHeap;
let heap = BinaryHeap::from([1, 3]);
assert_eq!(heap.len(), 2);
sourcepub fn is_empty(&self) -> bool
pub fn is_empty(&self) -> bool
Checks if the d-ary heap is empty.
Examples
Basic usage:
use dary_heap::BinaryHeap;
let mut heap = BinaryHeap::new();
assert!(heap.is_empty());
heap.push(3);
heap.push(5);
heap.push(1);
assert!(!heap.is_empty());
sourcepub fn drain(&mut self) -> Drain<'_, T> ⓘ
pub fn drain(&mut self) -> Drain<'_, T> ⓘ
Clears the d-ary 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 dary_heap::QuaternaryHeap;
let mut heap = QuaternaryHeap::from([1, 3]);
assert!(!heap.is_empty());
for x in heap.drain() {
println!("{x}");
}
assert!(heap.is_empty());
Trait Implementations§
source§impl<'de, T: Ord + Deserialize<'de>, const A: usize> Deserialize<'de> for DaryHeap<T, A>
impl<'de, T: Ord + Deserialize<'de>, const A: usize> Deserialize<'de> for DaryHeap<T, A>
source§fn deserialize<D>(deserializer: D) -> Result<Self, D::Error>where
D: Deserializer<'de>,
fn deserialize<D>(deserializer: D) -> Result<Self, D::Error>where D: Deserializer<'de>,
source§impl<'a, T: 'a + Ord + Copy, const D: usize> Extend<&'a T> for DaryHeap<T, D>
impl<'a, T: 'a + Ord + Copy, const D: usize> Extend<&'a T> for DaryHeap<T, D>
source§fn extend<I: IntoIterator<Item = &'a T>>(&mut self, iter: I)
fn extend<I: IntoIterator<Item = &'a T>>(&mut self, iter: I)
source§fn extend_one(&mut self, item: &'a T)
fn extend_one(&mut self, item: &'a T)
extend_one
)source§fn extend_reserve(&mut self, additional: usize)
fn extend_reserve(&mut self, additional: usize)
extend_one
)source§impl<T: Ord, const D: usize> Extend<T> for DaryHeap<T, D>
impl<T: Ord, const D: usize> Extend<T> for DaryHeap<T, D>
source§fn extend<I: IntoIterator<Item = T>>(&mut self, iter: I)
fn extend<I: IntoIterator<Item = T>>(&mut self, iter: I)
source§fn extend_one(&mut self, item: T)
fn extend_one(&mut self, item: T)
extend_one
)source§fn extend_reserve(&mut self, additional: usize)
fn extend_reserve(&mut self, additional: usize)
extend_one
)source§impl<T, const D: usize> IntoIterator for DaryHeap<T, D>
impl<T, const D: usize> IntoIterator for DaryHeap<T, D>
source§fn into_iter(self) -> IntoIter<T> ⓘ
fn into_iter(self) -> IntoIter<T> ⓘ
Creates a consuming iterator, that is, one that moves each value out of the d-ary heap in arbitrary order. The d-ary heap cannot be used after calling this.
Examples
Basic usage:
use dary_heap::BinaryHeap;
let heap = BinaryHeap::from([1, 2, 3, 4]);
// Print 1, 2, 3, 4 in arbitrary order
for x in heap.into_iter() {
// x has type i32, not &i32
println!("{x}");
}