1 //! A priority queue implemented with a binary heap.
3 //! Insertion and popping the largest element have *O*(log(*n*)) time complexity.
4 //! Checking the largest element is *O*(1). Converting a vector to a binary heap
5 //! can be done in-place, and has *O*(*n*) complexity. A binary heap can also be
6 //! converted to a sorted vector in-place, allowing it to be used for an *O*(*n* \* log(*n*))
11 //! This is a larger example that implements [Dijkstra's algorithm][dijkstra]
12 //! to solve the [shortest path problem][sssp] on a [directed graph][dir_graph].
13 //! It shows how to use [`BinaryHeap`] with custom types.
15 //! [dijkstra]: https://en.wikipedia.org/wiki/Dijkstra%27s_algorithm
16 //! [sssp]: https://en.wikipedia.org/wiki/Shortest_path_problem
17 //! [dir_graph]: https://en.wikipedia.org/wiki/Directed_graph
20 //! use std::cmp::Ordering;
21 //! use std::collections::BinaryHeap;
23 //! #[derive(Copy, Clone, Eq, PartialEq)]
29 //! // The priority queue depends on `Ord`.
30 //! // Explicitly implement the trait so the queue becomes a min-heap
31 //! // instead of a max-heap.
32 //! impl Ord for State {
33 //! fn cmp(&self, other: &Self) -> Ordering {
34 //! // Notice that the we flip the ordering on costs.
35 //! // In case of a tie we compare positions - this step is necessary
36 //! // to make implementations of `PartialEq` and `Ord` consistent.
37 //! other.cost.cmp(&self.cost)
38 //! .then_with(|| self.position.cmp(&other.position))
42 //! // `PartialOrd` needs to be implemented as well.
43 //! impl PartialOrd for State {
44 //! fn partial_cmp(&self, other: &Self) -> Option<Ordering> {
45 //! Some(self.cmp(other))
49 //! // Each node is represented as an `usize`, for a shorter implementation.
55 //! // Dijkstra's shortest path algorithm.
57 //! // Start at `start` and use `dist` to track the current shortest distance
58 //! // to each node. This implementation isn't memory-efficient as it may leave duplicate
59 //! // nodes in the queue. It also uses `usize::MAX` as a sentinel value,
60 //! // for a simpler implementation.
61 //! fn shortest_path(adj_list: &Vec<Vec<Edge>>, start: usize, goal: usize) -> Option<usize> {
62 //! // dist[node] = current shortest distance from `start` to `node`
63 //! let mut dist: Vec<_> = (0..adj_list.len()).map(|_| usize::MAX).collect();
65 //! let mut heap = BinaryHeap::new();
67 //! // We're at `start`, with a zero cost
69 //! heap.push(State { cost: 0, position: start });
71 //! // Examine the frontier with lower cost nodes first (min-heap)
72 //! while let Some(State { cost, position }) = heap.pop() {
73 //! // Alternatively we could have continued to find all shortest paths
74 //! if position == goal { return Some(cost); }
76 //! // Important as we may have already found a better way
77 //! if cost > dist[position] { continue; }
79 //! // For each node we can reach, see if we can find a way with
80 //! // a lower cost going through this node
81 //! for edge in &adj_list[position] {
82 //! let next = State { cost: cost + edge.cost, position: edge.node };
84 //! // If so, add it to the frontier and continue
85 //! if next.cost < dist[next.position] {
87 //! // Relaxation, we have now found a better way
88 //! dist[next.position] = next.cost;
93 //! // Goal not reachable
98 //! // This is the directed graph we're going to use.
99 //! // The node numbers correspond to the different states,
100 //! // and the edge weights symbolize the cost of moving
101 //! // from one node to another.
102 //! // Note that the edges are one-way.
105 //! // +-----------------+
108 //! // 0 -----> 1 -----> 3 ---> 4
112 //! // +------> 2 -------+ |
114 //! // +---------------+
116 //! // The graph is represented as an adjacency list where each index,
117 //! // corresponding to a node value, has a list of outgoing edges.
118 //! // Chosen for its efficiency.
119 //! let graph = vec![
121 //! vec![Edge { node: 2, cost: 10 },
122 //! Edge { node: 1, cost: 1 }],
124 //! vec![Edge { node: 3, cost: 2 }],
126 //! vec![Edge { node: 1, cost: 1 },
127 //! Edge { node: 3, cost: 3 },
128 //! Edge { node: 4, cost: 1 }],
130 //! vec![Edge { node: 0, cost: 7 },
131 //! Edge { node: 4, cost: 2 }],
135 //! assert_eq!(shortest_path(&graph, 0, 1), Some(1));
136 //! assert_eq!(shortest_path(&graph, 0, 3), Some(3));
137 //! assert_eq!(shortest_path(&graph, 3, 0), Some(7));
138 //! assert_eq!(shortest_path(&graph, 0, 4), Some(5));
139 //! assert_eq!(shortest_path(&graph, 4, 0), None);
143 #![allow(missing_docs)]
144 #![stable(feature = "rust1", since = "1.0.0")]
147 use core::iter::{FromIterator, FusedIterator, InPlaceIterable, SourceIter, TrustedLen};
148 use core::mem::{self, swap, ManuallyDrop};
149 use core::ops::{Deref, DerefMut};
153 use crate::vec::{self, AsIntoIter, Vec};
155 use super::SpecExtend;
157 /// A priority queue implemented with a binary heap.
159 /// This will be a max-heap.
161 /// It is a logic error for an item to be modified in such a way that the
162 /// item's ordering relative to any other item, as determined by the `Ord`
163 /// trait, changes while it is in the heap. This is normally only possible
164 /// through `Cell`, `RefCell`, global state, I/O, or unsafe code. The
165 /// behavior resulting from such a logic error is not specified, but will
166 /// not result in undefined behavior. This could include panics, incorrect
167 /// results, aborts, memory leaks, and non-termination.
172 /// use std::collections::BinaryHeap;
174 /// // Type inference lets us omit an explicit type signature (which
175 /// // would be `BinaryHeap<i32>` in this example).
176 /// let mut heap = BinaryHeap::new();
178 /// // We can use peek to look at the next item in the heap. In this case,
179 /// // there's no items in there yet so we get None.
180 /// assert_eq!(heap.peek(), None);
182 /// // Let's add some scores...
187 /// // Now peek shows the most important item in the heap.
188 /// assert_eq!(heap.peek(), Some(&5));
190 /// // We can check the length of a heap.
191 /// assert_eq!(heap.len(), 3);
193 /// // We can iterate over the items in the heap, although they are returned in
194 /// // a random order.
196 /// println!("{}", x);
199 /// // If we instead pop these scores, they should come back in order.
200 /// assert_eq!(heap.pop(), Some(5));
201 /// assert_eq!(heap.pop(), Some(2));
202 /// assert_eq!(heap.pop(), Some(1));
203 /// assert_eq!(heap.pop(), None);
205 /// // We can clear the heap of any remaining items.
208 /// // The heap should now be empty.
209 /// assert!(heap.is_empty())
212 /// A `BinaryHeap` with a known list of items can be initialized from an array:
215 /// use std::collections::BinaryHeap;
217 /// let heap = BinaryHeap::from([1, 5, 2]);
222 /// Either `std::cmp::Reverse` or a custom `Ord` implementation can be used to
223 /// make `BinaryHeap` a min-heap. This makes `heap.pop()` return the smallest
224 /// value instead of the greatest one.
227 /// use std::collections::BinaryHeap;
228 /// use std::cmp::Reverse;
230 /// let mut heap = BinaryHeap::new();
232 /// // Wrap values in `Reverse`
233 /// heap.push(Reverse(1));
234 /// heap.push(Reverse(5));
235 /// heap.push(Reverse(2));
237 /// // If we pop these scores now, they should come back in the reverse order.
238 /// assert_eq!(heap.pop(), Some(Reverse(1)));
239 /// assert_eq!(heap.pop(), Some(Reverse(2)));
240 /// assert_eq!(heap.pop(), Some(Reverse(5)));
241 /// assert_eq!(heap.pop(), None);
244 /// # Time complexity
246 /// | [push] | [pop] | [peek]/[peek\_mut] |
247 /// |--------|-----------|--------------------|
248 /// | O(1)~ | *O*(log(*n*)) | *O*(1) |
250 /// The value for `push` is an expected cost; the method documentation gives a
251 /// more detailed analysis.
253 /// [push]: BinaryHeap::push
254 /// [pop]: BinaryHeap::pop
255 /// [peek]: BinaryHeap::peek
256 /// [peek\_mut]: BinaryHeap::peek_mut
257 #[stable(feature = "rust1", since = "1.0.0")]
258 #[cfg_attr(not(test), rustc_diagnostic_item = "BinaryHeap")]
259 pub struct BinaryHeap<T> {
263 /// Structure wrapping a mutable reference to the greatest item on a
266 /// This `struct` is created by the [`peek_mut`] method on [`BinaryHeap`]. See
267 /// its documentation for more.
269 /// [`peek_mut`]: BinaryHeap::peek_mut
270 #[stable(feature = "binary_heap_peek_mut", since = "1.12.0")]
271 pub struct PeekMut<'a, T: 'a + Ord> {
272 heap: &'a mut BinaryHeap<T>,
276 #[stable(feature = "collection_debug", since = "1.17.0")]
277 impl<T: Ord + fmt::Debug> fmt::Debug for PeekMut<'_, T> {
278 fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
279 f.debug_tuple("PeekMut").field(&self.heap.data[0]).finish()
283 #[stable(feature = "binary_heap_peek_mut", since = "1.12.0")]
284 impl<T: Ord> Drop for PeekMut<'_, T> {
287 // SAFETY: PeekMut is only instantiated for non-empty heaps.
288 unsafe { self.heap.sift_down(0) };
293 #[stable(feature = "binary_heap_peek_mut", since = "1.12.0")]
294 impl<T: Ord> Deref for PeekMut<'_, T> {
296 fn deref(&self) -> &T {
297 debug_assert!(!self.heap.is_empty());
298 // SAFE: PeekMut is only instantiated for non-empty heaps
299 unsafe { self.heap.data.get_unchecked(0) }
303 #[stable(feature = "binary_heap_peek_mut", since = "1.12.0")]
304 impl<T: Ord> DerefMut for PeekMut<'_, T> {
305 fn deref_mut(&mut self) -> &mut T {
306 debug_assert!(!self.heap.is_empty());
308 // SAFE: PeekMut is only instantiated for non-empty heaps
309 unsafe { self.heap.data.get_unchecked_mut(0) }
313 impl<'a, T: Ord> PeekMut<'a, T> {
314 /// Removes the peeked value from the heap and returns it.
315 #[stable(feature = "binary_heap_peek_mut_pop", since = "1.18.0")]
316 pub fn pop(mut this: PeekMut<'a, T>) -> T {
317 let value = this.heap.pop().unwrap();
323 #[stable(feature = "rust1", since = "1.0.0")]
324 impl<T: Clone> Clone for BinaryHeap<T> {
325 fn clone(&self) -> Self {
326 BinaryHeap { data: self.data.clone() }
329 fn clone_from(&mut self, source: &Self) {
330 self.data.clone_from(&source.data);
334 #[stable(feature = "rust1", since = "1.0.0")]
335 impl<T: Ord> Default for BinaryHeap<T> {
336 /// Creates an empty `BinaryHeap<T>`.
338 fn default() -> BinaryHeap<T> {
343 #[stable(feature = "binaryheap_debug", since = "1.4.0")]
344 impl<T: fmt::Debug> fmt::Debug for BinaryHeap<T> {
345 fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
346 f.debug_list().entries(self.iter()).finish()
350 impl<T: Ord> BinaryHeap<T> {
351 /// Creates an empty `BinaryHeap` as a max-heap.
358 /// use std::collections::BinaryHeap;
359 /// let mut heap = BinaryHeap::new();
362 #[stable(feature = "rust1", since = "1.0.0")]
363 pub fn new() -> BinaryHeap<T> {
364 BinaryHeap { data: vec![] }
367 /// Creates an empty `BinaryHeap` with a specific capacity.
368 /// This preallocates enough memory for `capacity` elements,
369 /// so that the `BinaryHeap` does not have to be reallocated
370 /// until it contains at least that many values.
377 /// use std::collections::BinaryHeap;
378 /// let mut heap = BinaryHeap::with_capacity(10);
381 #[stable(feature = "rust1", since = "1.0.0")]
382 pub fn with_capacity(capacity: usize) -> BinaryHeap<T> {
383 BinaryHeap { data: Vec::with_capacity(capacity) }
386 /// Returns a mutable reference to the greatest item in the binary heap, or
387 /// `None` if it is empty.
389 /// Note: If the `PeekMut` value is leaked, the heap may be in an
390 /// inconsistent state.
397 /// use std::collections::BinaryHeap;
398 /// let mut heap = BinaryHeap::new();
399 /// assert!(heap.peek_mut().is_none());
405 /// let mut val = heap.peek_mut().unwrap();
408 /// assert_eq!(heap.peek(), Some(&2));
411 /// # Time complexity
413 /// If the item is modified then the worst case time complexity is *O*(log(*n*)),
414 /// otherwise it's *O*(1).
415 #[stable(feature = "binary_heap_peek_mut", since = "1.12.0")]
416 pub fn peek_mut(&mut self) -> Option<PeekMut<'_, T>> {
417 if self.is_empty() { None } else { Some(PeekMut { heap: self, sift: false }) }
420 /// Removes the greatest item from the binary heap and returns it, or `None` if it
428 /// use std::collections::BinaryHeap;
429 /// let mut heap = BinaryHeap::from(vec![1, 3]);
431 /// assert_eq!(heap.pop(), Some(3));
432 /// assert_eq!(heap.pop(), Some(1));
433 /// assert_eq!(heap.pop(), None);
436 /// # Time complexity
438 /// The worst case cost of `pop` on a heap containing *n* elements is *O*(log(*n*)).
439 #[stable(feature = "rust1", since = "1.0.0")]
440 pub fn pop(&mut self) -> Option<T> {
441 self.data.pop().map(|mut item| {
442 if !self.is_empty() {
443 swap(&mut item, &mut self.data[0]);
444 // SAFETY: !self.is_empty() means that self.len() > 0
445 unsafe { self.sift_down_to_bottom(0) };
451 /// Pushes an item onto the binary heap.
458 /// use std::collections::BinaryHeap;
459 /// let mut heap = BinaryHeap::new();
464 /// assert_eq!(heap.len(), 3);
465 /// assert_eq!(heap.peek(), Some(&5));
468 /// # Time complexity
470 /// The expected cost of `push`, averaged over every possible ordering of
471 /// the elements being pushed, and over a sufficiently large number of
472 /// pushes, is *O*(1). This is the most meaningful cost metric when pushing
473 /// elements that are *not* already in any sorted pattern.
475 /// The time complexity degrades if elements are pushed in predominantly
476 /// ascending order. In the worst case, elements are pushed in ascending
477 /// sorted order and the amortized cost per push is *O*(log(*n*)) against a heap
478 /// containing *n* elements.
480 /// The worst case cost of a *single* call to `push` is *O*(*n*). The worst case
481 /// occurs when capacity is exhausted and needs a resize. The resize cost
482 /// has been amortized in the previous figures.
483 #[stable(feature = "rust1", since = "1.0.0")]
484 pub fn push(&mut self, item: T) {
485 let old_len = self.len();
486 self.data.push(item);
487 // SAFETY: Since we pushed a new item it means that
488 // old_len = self.len() - 1 < self.len()
489 unsafe { self.sift_up(0, old_len) };
492 /// Consumes the `BinaryHeap` and returns a vector in sorted
493 /// (ascending) order.
500 /// use std::collections::BinaryHeap;
502 /// let mut heap = BinaryHeap::from(vec![1, 2, 4, 5, 7]);
506 /// let vec = heap.into_sorted_vec();
507 /// assert_eq!(vec, [1, 2, 3, 4, 5, 6, 7]);
509 #[stable(feature = "binary_heap_extras_15", since = "1.5.0")]
510 pub fn into_sorted_vec(mut self) -> Vec<T> {
511 let mut end = self.len();
514 // SAFETY: `end` goes from `self.len() - 1` to 1 (both included),
515 // so it's always a valid index to access.
516 // It is safe to access index 0 (i.e. `ptr`), because
517 // 1 <= end < self.len(), which means self.len() >= 2.
519 let ptr = self.data.as_mut_ptr();
520 ptr::swap(ptr, ptr.add(end));
522 // SAFETY: `end` goes from `self.len() - 1` to 1 (both included) so:
523 // 0 < 1 <= end <= self.len() - 1 < self.len()
524 // Which means 0 < end and end < self.len().
525 unsafe { self.sift_down_range(0, end) };
530 // The implementations of sift_up and sift_down use unsafe blocks in
531 // order to move an element out of the vector (leaving behind a
532 // hole), shift along the others and move the removed element back into the
533 // vector at the final location of the hole.
534 // The `Hole` type is used to represent this, and make sure
535 // the hole is filled back at the end of its scope, even on panic.
536 // Using a hole reduces the constant factor compared to using swaps,
537 // which involves twice as many moves.
541 /// The caller must guarantee that `pos < self.len()`.
542 unsafe fn sift_up(&mut self, start: usize, pos: usize) -> usize {
543 // Take out the value at `pos` and create a hole.
544 // SAFETY: The caller guarantees that pos < self.len()
545 let mut hole = unsafe { Hole::new(&mut self.data, pos) };
547 while hole.pos() > start {
548 let parent = (hole.pos() - 1) / 2;
550 // SAFETY: hole.pos() > start >= 0, which means hole.pos() > 0
551 // and so hole.pos() - 1 can't underflow.
552 // This guarantees that parent < hole.pos() so
553 // it's a valid index and also != hole.pos().
554 if hole.element() <= unsafe { hole.get(parent) } {
558 // SAFETY: Same as above
559 unsafe { hole.move_to(parent) };
565 /// Take an element at `pos` and move it down the heap,
566 /// while its children are larger.
570 /// The caller must guarantee that `pos < end <= self.len()`.
571 unsafe fn sift_down_range(&mut self, pos: usize, end: usize) {
572 // SAFETY: The caller guarantees that pos < end <= self.len().
573 let mut hole = unsafe { Hole::new(&mut self.data, pos) };
574 let mut child = 2 * hole.pos() + 1;
576 // Loop invariant: child == 2 * hole.pos() + 1.
577 while child <= end.saturating_sub(2) {
578 // compare with the greater of the two children
579 // SAFETY: child < end - 1 < self.len() and
580 // child + 1 < end <= self.len(), so they're valid indexes.
581 // child == 2 * hole.pos() + 1 != hole.pos() and
582 // child + 1 == 2 * hole.pos() + 2 != hole.pos().
583 // FIXME: 2 * hole.pos() + 1 or 2 * hole.pos() + 2 could overflow
585 child += unsafe { hole.get(child) <= hole.get(child + 1) } as usize;
587 // if we are already in order, stop.
588 // SAFETY: child is now either the old child or the old child+1
589 // We already proven that both are < self.len() and != hole.pos()
590 if hole.element() >= unsafe { hole.get(child) } {
594 // SAFETY: same as above.
595 unsafe { hole.move_to(child) };
596 child = 2 * hole.pos() + 1;
599 // SAFETY: && short circuit, which means that in the
600 // second condition it's already true that child == end - 1 < self.len().
601 if child == end - 1 && hole.element() < unsafe { hole.get(child) } {
602 // SAFETY: child is already proven to be a valid index and
603 // child == 2 * hole.pos() + 1 != hole.pos().
604 unsafe { hole.move_to(child) };
610 /// The caller must guarantee that `pos < self.len()`.
611 unsafe fn sift_down(&mut self, pos: usize) {
612 let len = self.len();
613 // SAFETY: pos < len is guaranteed by the caller and
614 // obviously len = self.len() <= self.len().
615 unsafe { self.sift_down_range(pos, len) };
618 /// Take an element at `pos` and move it all the way down the heap,
619 /// then sift it up to its position.
621 /// Note: This is faster when the element is known to be large / should
622 /// be closer to the bottom.
626 /// The caller must guarantee that `pos < self.len()`.
627 unsafe fn sift_down_to_bottom(&mut self, mut pos: usize) {
628 let end = self.len();
631 // SAFETY: The caller guarantees that pos < self.len().
632 let mut hole = unsafe { Hole::new(&mut self.data, pos) };
633 let mut child = 2 * hole.pos() + 1;
635 // Loop invariant: child == 2 * hole.pos() + 1.
636 while child <= end.saturating_sub(2) {
637 // SAFETY: child < end - 1 < self.len() and
638 // child + 1 < end <= self.len(), so they're valid indexes.
639 // child == 2 * hole.pos() + 1 != hole.pos() and
640 // child + 1 == 2 * hole.pos() + 2 != hole.pos().
641 // FIXME: 2 * hole.pos() + 1 or 2 * hole.pos() + 2 could overflow
643 child += unsafe { hole.get(child) <= hole.get(child + 1) } as usize;
645 // SAFETY: Same as above
646 unsafe { hole.move_to(child) };
647 child = 2 * hole.pos() + 1;
650 if child == end - 1 {
651 // SAFETY: child == end - 1 < self.len(), so it's a valid index
652 // and child == 2 * hole.pos() + 1 != hole.pos().
653 unsafe { hole.move_to(child) };
658 // SAFETY: pos is the position in the hole and was already proven
659 // to be a valid index.
660 unsafe { self.sift_up(start, pos) };
663 fn rebuild(&mut self) {
664 let mut n = self.len() / 2;
667 // SAFETY: n starts from self.len() / 2 and goes down to 0.
668 // The only case when !(n < self.len()) is if
669 // self.len() == 0, but it's ruled out by the loop condition.
670 unsafe { self.sift_down(n) };
674 /// Moves all the elements of `other` into `self`, leaving `other` empty.
681 /// use std::collections::BinaryHeap;
683 /// let v = vec![-10, 1, 2, 3, 3];
684 /// let mut a = BinaryHeap::from(v);
686 /// let v = vec![-20, 5, 43];
687 /// let mut b = BinaryHeap::from(v);
689 /// a.append(&mut b);
691 /// assert_eq!(a.into_sorted_vec(), [-20, -10, 1, 2, 3, 3, 5, 43]);
692 /// assert!(b.is_empty());
694 #[stable(feature = "binary_heap_append", since = "1.11.0")]
695 pub fn append(&mut self, other: &mut Self) {
696 if self.len() < other.len() {
700 if other.is_empty() {
705 fn log2_fast(x: usize) -> usize {
706 (usize::BITS - x.leading_zeros() - 1) as usize
709 // `rebuild` takes O(len1 + len2) operations
710 // and about 2 * (len1 + len2) comparisons in the worst case
711 // while `extend` takes O(len2 * log(len1)) operations
712 // and about 1 * len2 * log_2(len1) comparisons in the worst case,
713 // assuming len1 >= len2. For larger heaps, the crossover point
714 // no longer follows this reasoning and was determined empirically.
716 fn better_to_rebuild(len1: usize, len2: usize) -> bool {
717 let tot_len = len1 + len2;
719 2 * tot_len < len2 * log2_fast(len1)
721 2 * tot_len < len2 * 11
725 if better_to_rebuild(self.len(), other.len()) {
726 self.data.append(&mut other.data);
729 self.extend(other.drain());
733 /// Returns an iterator which retrieves elements in heap order.
734 /// The retrieved elements are removed from the original heap.
735 /// The remaining elements will be removed on drop in heap order.
738 /// * `.drain_sorted()` is *O*(*n* \* log(*n*)); much slower than `.drain()`.
739 /// You should use the latter for most cases.
746 /// #![feature(binary_heap_drain_sorted)]
747 /// use std::collections::BinaryHeap;
749 /// let mut heap = BinaryHeap::from(vec![1, 2, 3, 4, 5]);
750 /// assert_eq!(heap.len(), 5);
752 /// drop(heap.drain_sorted()); // removes all elements in heap order
753 /// assert_eq!(heap.len(), 0);
756 #[unstable(feature = "binary_heap_drain_sorted", issue = "59278")]
757 pub fn drain_sorted(&mut self) -> DrainSorted<'_, T> {
758 DrainSorted { inner: self }
761 /// Retains only the elements specified by the predicate.
763 /// In other words, remove all elements `e` such that `f(&e)` returns
764 /// `false`. The elements are visited in unsorted (and unspecified) order.
771 /// #![feature(binary_heap_retain)]
772 /// use std::collections::BinaryHeap;
774 /// let mut heap = BinaryHeap::from(vec![-10, -5, 1, 2, 4, 13]);
776 /// heap.retain(|x| x % 2 == 0); // only keep even numbers
778 /// assert_eq!(heap.into_sorted_vec(), [-10, 2, 4])
780 #[unstable(feature = "binary_heap_retain", issue = "71503")]
781 pub fn retain<F>(&mut self, f: F)
783 F: FnMut(&T) -> bool,
790 impl<T> BinaryHeap<T> {
791 /// Returns an iterator visiting all values in the underlying vector, in
799 /// use std::collections::BinaryHeap;
800 /// let heap = BinaryHeap::from(vec![1, 2, 3, 4]);
802 /// // Print 1, 2, 3, 4 in arbitrary order
803 /// for x in heap.iter() {
804 /// println!("{}", x);
807 #[stable(feature = "rust1", since = "1.0.0")]
808 pub fn iter(&self) -> Iter<'_, T> {
809 Iter { iter: self.data.iter() }
812 /// Returns an iterator which retrieves elements in heap order.
813 /// This method consumes the original heap.
820 /// #![feature(binary_heap_into_iter_sorted)]
821 /// use std::collections::BinaryHeap;
822 /// let heap = BinaryHeap::from(vec![1, 2, 3, 4, 5]);
824 /// assert_eq!(heap.into_iter_sorted().take(2).collect::<Vec<_>>(), vec![5, 4]);
826 #[unstable(feature = "binary_heap_into_iter_sorted", issue = "59278")]
827 pub fn into_iter_sorted(self) -> IntoIterSorted<T> {
828 IntoIterSorted { inner: self }
831 /// Returns the greatest item in the binary heap, or `None` if it is empty.
838 /// use std::collections::BinaryHeap;
839 /// let mut heap = BinaryHeap::new();
840 /// assert_eq!(heap.peek(), None);
845 /// assert_eq!(heap.peek(), Some(&5));
849 /// # Time complexity
851 /// Cost is *O*(1) in the worst case.
852 #[stable(feature = "rust1", since = "1.0.0")]
853 pub fn peek(&self) -> Option<&T> {
857 /// Returns the number of elements the binary heap can hold without reallocating.
864 /// use std::collections::BinaryHeap;
865 /// let mut heap = BinaryHeap::with_capacity(100);
866 /// assert!(heap.capacity() >= 100);
869 #[stable(feature = "rust1", since = "1.0.0")]
870 pub fn capacity(&self) -> usize {
874 /// Reserves the minimum capacity for exactly `additional` more elements to be inserted in the
875 /// given `BinaryHeap`. Does nothing if the capacity is already sufficient.
877 /// Note that the allocator may give the collection more space than it requests. Therefore
878 /// capacity can not be relied upon to be precisely minimal. Prefer [`reserve`] if future
879 /// insertions are expected.
883 /// Panics if the new capacity overflows `usize`.
890 /// use std::collections::BinaryHeap;
891 /// let mut heap = BinaryHeap::new();
892 /// heap.reserve_exact(100);
893 /// assert!(heap.capacity() >= 100);
897 /// [`reserve`]: BinaryHeap::reserve
898 #[stable(feature = "rust1", since = "1.0.0")]
899 pub fn reserve_exact(&mut self, additional: usize) {
900 self.data.reserve_exact(additional);
903 /// Reserves capacity for at least `additional` more elements to be inserted in the
904 /// `BinaryHeap`. The collection may reserve more space to avoid frequent reallocations.
908 /// Panics if the new capacity overflows `usize`.
915 /// use std::collections::BinaryHeap;
916 /// let mut heap = BinaryHeap::new();
917 /// heap.reserve(100);
918 /// assert!(heap.capacity() >= 100);
921 #[stable(feature = "rust1", since = "1.0.0")]
922 pub fn reserve(&mut self, additional: usize) {
923 self.data.reserve(additional);
926 /// Discards as much additional capacity as possible.
933 /// use std::collections::BinaryHeap;
934 /// let mut heap: BinaryHeap<i32> = BinaryHeap::with_capacity(100);
936 /// assert!(heap.capacity() >= 100);
937 /// heap.shrink_to_fit();
938 /// assert!(heap.capacity() == 0);
940 #[stable(feature = "rust1", since = "1.0.0")]
941 pub fn shrink_to_fit(&mut self) {
942 self.data.shrink_to_fit();
945 /// Discards capacity with a lower bound.
947 /// The capacity will remain at least as large as both the length
948 /// and the supplied value.
950 /// If the current capacity is less than the lower limit, this is a no-op.
955 /// #![feature(shrink_to)]
956 /// use std::collections::BinaryHeap;
957 /// let mut heap: BinaryHeap<i32> = BinaryHeap::with_capacity(100);
959 /// assert!(heap.capacity() >= 100);
960 /// heap.shrink_to(10);
961 /// assert!(heap.capacity() >= 10);
964 #[unstable(feature = "shrink_to", reason = "new API", issue = "56431")]
965 pub fn shrink_to(&mut self, min_capacity: usize) {
966 self.data.shrink_to(min_capacity)
969 /// Returns a slice of all values in the underlying vector, in arbitrary
977 /// #![feature(binary_heap_as_slice)]
978 /// use std::collections::BinaryHeap;
979 /// use std::io::{self, Write};
981 /// let heap = BinaryHeap::from(vec![1, 2, 3, 4, 5, 6, 7]);
983 /// io::sink().write(heap.as_slice()).unwrap();
985 #[unstable(feature = "binary_heap_as_slice", issue = "83659")]
986 pub fn as_slice(&self) -> &[T] {
990 /// Consumes the `BinaryHeap` and returns the underlying vector
991 /// in arbitrary order.
998 /// use std::collections::BinaryHeap;
999 /// let heap = BinaryHeap::from(vec![1, 2, 3, 4, 5, 6, 7]);
1000 /// let vec = heap.into_vec();
1002 /// // Will print in some order
1004 /// println!("{}", x);
1007 #[stable(feature = "binary_heap_extras_15", since = "1.5.0")]
1008 pub fn into_vec(self) -> Vec<T> {
1012 /// Returns the length of the binary heap.
1019 /// use std::collections::BinaryHeap;
1020 /// let heap = BinaryHeap::from(vec![1, 3]);
1022 /// assert_eq!(heap.len(), 2);
1024 #[doc(alias = "length")]
1025 #[stable(feature = "rust1", since = "1.0.0")]
1026 pub fn len(&self) -> usize {
1030 /// Checks if the binary heap is empty.
1037 /// use std::collections::BinaryHeap;
1038 /// let mut heap = BinaryHeap::new();
1040 /// assert!(heap.is_empty());
1046 /// assert!(!heap.is_empty());
1048 #[stable(feature = "rust1", since = "1.0.0")]
1049 pub fn is_empty(&self) -> bool {
1053 /// Clears the binary heap, returning an iterator over the removed elements.
1055 /// The elements are removed in arbitrary order.
1062 /// use std::collections::BinaryHeap;
1063 /// let mut heap = BinaryHeap::from(vec![1, 3]);
1065 /// assert!(!heap.is_empty());
1067 /// for x in heap.drain() {
1068 /// println!("{}", x);
1071 /// assert!(heap.is_empty());
1074 #[stable(feature = "drain", since = "1.6.0")]
1075 pub fn drain(&mut self) -> Drain<'_, T> {
1076 Drain { iter: self.data.drain(..) }
1079 /// Drops all items from the binary heap.
1086 /// use std::collections::BinaryHeap;
1087 /// let mut heap = BinaryHeap::from(vec![1, 3]);
1089 /// assert!(!heap.is_empty());
1093 /// assert!(heap.is_empty());
1095 #[stable(feature = "rust1", since = "1.0.0")]
1096 pub fn clear(&mut self) {
1101 /// Hole represents a hole in a slice i.e., an index without valid value
1102 /// (because it was moved from or duplicated).
1103 /// In drop, `Hole` will restore the slice by filling the hole
1104 /// position with the value that was originally removed.
1105 struct Hole<'a, T: 'a> {
1107 elt: ManuallyDrop<T>,
1111 impl<'a, T> Hole<'a, T> {
1112 /// Create a new `Hole` at index `pos`.
1114 /// Unsafe because pos must be within the data slice.
1116 unsafe fn new(data: &'a mut [T], pos: usize) -> Self {
1117 debug_assert!(pos < data.len());
1118 // SAFE: pos should be inside the slice
1119 let elt = unsafe { ptr::read(data.get_unchecked(pos)) };
1120 Hole { data, elt: ManuallyDrop::new(elt), pos }
1124 fn pos(&self) -> usize {
1128 /// Returns a reference to the element removed.
1130 fn element(&self) -> &T {
1134 /// Returns a reference to the element at `index`.
1136 /// Unsafe because index must be within the data slice and not equal to pos.
1138 unsafe fn get(&self, index: usize) -> &T {
1139 debug_assert!(index != self.pos);
1140 debug_assert!(index < self.data.len());
1141 unsafe { self.data.get_unchecked(index) }
1144 /// Move hole to new location
1146 /// Unsafe because index must be within the data slice and not equal to pos.
1148 unsafe fn move_to(&mut self, index: usize) {
1149 debug_assert!(index != self.pos);
1150 debug_assert!(index < self.data.len());
1152 let ptr = self.data.as_mut_ptr();
1153 let index_ptr: *const _ = ptr.add(index);
1154 let hole_ptr = ptr.add(self.pos);
1155 ptr::copy_nonoverlapping(index_ptr, hole_ptr, 1);
1161 impl<T> Drop for Hole<'_, T> {
1163 fn drop(&mut self) {
1164 // fill the hole again
1167 ptr::copy_nonoverlapping(&*self.elt, self.data.get_unchecked_mut(pos), 1);
1172 /// An iterator over the elements of a `BinaryHeap`.
1174 /// This `struct` is created by [`BinaryHeap::iter()`]. See its
1175 /// documentation for more.
1177 /// [`iter`]: BinaryHeap::iter
1178 #[stable(feature = "rust1", since = "1.0.0")]
1179 pub struct Iter<'a, T: 'a> {
1180 iter: slice::Iter<'a, T>,
1183 #[stable(feature = "collection_debug", since = "1.17.0")]
1184 impl<T: fmt::Debug> fmt::Debug for Iter<'_, T> {
1185 fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
1186 f.debug_tuple("Iter").field(&self.iter.as_slice()).finish()
1190 // FIXME(#26925) Remove in favor of `#[derive(Clone)]`
1191 #[stable(feature = "rust1", since = "1.0.0")]
1192 impl<T> Clone for Iter<'_, T> {
1193 fn clone(&self) -> Self {
1194 Iter { iter: self.iter.clone() }
1198 #[stable(feature = "rust1", since = "1.0.0")]
1199 impl<'a, T> Iterator for Iter<'a, T> {
1203 fn next(&mut self) -> Option<&'a T> {
1208 fn size_hint(&self) -> (usize, Option<usize>) {
1209 self.iter.size_hint()
1213 fn last(self) -> Option<&'a T> {
1218 #[stable(feature = "rust1", since = "1.0.0")]
1219 impl<'a, T> DoubleEndedIterator for Iter<'a, T> {
1221 fn next_back(&mut self) -> Option<&'a T> {
1222 self.iter.next_back()
1226 #[stable(feature = "rust1", since = "1.0.0")]
1227 impl<T> ExactSizeIterator for Iter<'_, T> {
1228 fn is_empty(&self) -> bool {
1229 self.iter.is_empty()
1233 #[stable(feature = "fused", since = "1.26.0")]
1234 impl<T> FusedIterator for Iter<'_, T> {}
1236 /// An owning iterator over the elements of a `BinaryHeap`.
1238 /// This `struct` is created by [`BinaryHeap::into_iter()`]
1239 /// (provided by the `IntoIterator` trait). See its documentation for more.
1241 /// [`into_iter`]: BinaryHeap::into_iter
1242 #[stable(feature = "rust1", since = "1.0.0")]
1244 pub struct IntoIter<T> {
1245 iter: vec::IntoIter<T>,
1248 #[stable(feature = "collection_debug", since = "1.17.0")]
1249 impl<T: fmt::Debug> fmt::Debug for IntoIter<T> {
1250 fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
1251 f.debug_tuple("IntoIter").field(&self.iter.as_slice()).finish()
1255 #[stable(feature = "rust1", since = "1.0.0")]
1256 impl<T> Iterator for IntoIter<T> {
1260 fn next(&mut self) -> Option<T> {
1265 fn size_hint(&self) -> (usize, Option<usize>) {
1266 self.iter.size_hint()
1270 #[stable(feature = "rust1", since = "1.0.0")]
1271 impl<T> DoubleEndedIterator for IntoIter<T> {
1273 fn next_back(&mut self) -> Option<T> {
1274 self.iter.next_back()
1278 #[stable(feature = "rust1", since = "1.0.0")]
1279 impl<T> ExactSizeIterator for IntoIter<T> {
1280 fn is_empty(&self) -> bool {
1281 self.iter.is_empty()
1285 #[stable(feature = "fused", since = "1.26.0")]
1286 impl<T> FusedIterator for IntoIter<T> {}
1288 #[unstable(issue = "none", feature = "inplace_iteration")]
1289 unsafe impl<T> SourceIter for IntoIter<T> {
1290 type Source = IntoIter<T>;
1293 unsafe fn as_inner(&mut self) -> &mut Self::Source {
1298 #[unstable(issue = "none", feature = "inplace_iteration")]
1299 unsafe impl<I> InPlaceIterable for IntoIter<I> {}
1301 impl<I> AsIntoIter for IntoIter<I> {
1304 fn as_into_iter(&mut self) -> &mut vec::IntoIter<Self::Item> {
1309 #[unstable(feature = "binary_heap_into_iter_sorted", issue = "59278")]
1310 #[derive(Clone, Debug)]
1311 pub struct IntoIterSorted<T> {
1312 inner: BinaryHeap<T>,
1315 #[unstable(feature = "binary_heap_into_iter_sorted", issue = "59278")]
1316 impl<T: Ord> Iterator for IntoIterSorted<T> {
1320 fn next(&mut self) -> Option<T> {
1325 fn size_hint(&self) -> (usize, Option<usize>) {
1326 let exact = self.inner.len();
1327 (exact, Some(exact))
1331 #[unstable(feature = "binary_heap_into_iter_sorted", issue = "59278")]
1332 impl<T: Ord> ExactSizeIterator for IntoIterSorted<T> {}
1334 #[unstable(feature = "binary_heap_into_iter_sorted", issue = "59278")]
1335 impl<T: Ord> FusedIterator for IntoIterSorted<T> {}
1337 #[unstable(feature = "trusted_len", issue = "37572")]
1338 unsafe impl<T: Ord> TrustedLen for IntoIterSorted<T> {}
1340 /// A draining iterator over the elements of a `BinaryHeap`.
1342 /// This `struct` is created by [`BinaryHeap::drain()`]. See its
1343 /// documentation for more.
1345 /// [`drain`]: BinaryHeap::drain
1346 #[stable(feature = "drain", since = "1.6.0")]
1348 pub struct Drain<'a, T: 'a> {
1349 iter: vec::Drain<'a, T>,
1352 #[stable(feature = "drain", since = "1.6.0")]
1353 impl<T> Iterator for Drain<'_, T> {
1357 fn next(&mut self) -> Option<T> {
1362 fn size_hint(&self) -> (usize, Option<usize>) {
1363 self.iter.size_hint()
1367 #[stable(feature = "drain", since = "1.6.0")]
1368 impl<T> DoubleEndedIterator for Drain<'_, T> {
1370 fn next_back(&mut self) -> Option<T> {
1371 self.iter.next_back()
1375 #[stable(feature = "drain", since = "1.6.0")]
1376 impl<T> ExactSizeIterator for Drain<'_, T> {
1377 fn is_empty(&self) -> bool {
1378 self.iter.is_empty()
1382 #[stable(feature = "fused", since = "1.26.0")]
1383 impl<T> FusedIterator for Drain<'_, T> {}
1385 /// A draining iterator over the elements of a `BinaryHeap`.
1387 /// This `struct` is created by [`BinaryHeap::drain_sorted()`]. See its
1388 /// documentation for more.
1390 /// [`drain_sorted`]: BinaryHeap::drain_sorted
1391 #[unstable(feature = "binary_heap_drain_sorted", issue = "59278")]
1393 pub struct DrainSorted<'a, T: Ord> {
1394 inner: &'a mut BinaryHeap<T>,
1397 #[unstable(feature = "binary_heap_drain_sorted", issue = "59278")]
1398 impl<'a, T: Ord> Drop for DrainSorted<'a, T> {
1399 /// Removes heap elements in heap order.
1400 fn drop(&mut self) {
1401 struct DropGuard<'r, 'a, T: Ord>(&'r mut DrainSorted<'a, T>);
1403 impl<'r, 'a, T: Ord> Drop for DropGuard<'r, 'a, T> {
1404 fn drop(&mut self) {
1405 while self.0.inner.pop().is_some() {}
1409 while let Some(item) = self.inner.pop() {
1410 let guard = DropGuard(self);
1417 #[unstable(feature = "binary_heap_drain_sorted", issue = "59278")]
1418 impl<T: Ord> Iterator for DrainSorted<'_, T> {
1422 fn next(&mut self) -> Option<T> {
1427 fn size_hint(&self) -> (usize, Option<usize>) {
1428 let exact = self.inner.len();
1429 (exact, Some(exact))
1433 #[unstable(feature = "binary_heap_drain_sorted", issue = "59278")]
1434 impl<T: Ord> ExactSizeIterator for DrainSorted<'_, T> {}
1436 #[unstable(feature = "binary_heap_drain_sorted", issue = "59278")]
1437 impl<T: Ord> FusedIterator for DrainSorted<'_, T> {}
1439 #[unstable(feature = "trusted_len", issue = "37572")]
1440 unsafe impl<T: Ord> TrustedLen for DrainSorted<'_, T> {}
1442 #[stable(feature = "binary_heap_extras_15", since = "1.5.0")]
1443 impl<T: Ord> From<Vec<T>> for BinaryHeap<T> {
1444 /// Converts a `Vec<T>` into a `BinaryHeap<T>`.
1446 /// This conversion happens in-place, and has *O*(*n*) time complexity.
1447 fn from(vec: Vec<T>) -> BinaryHeap<T> {
1448 let mut heap = BinaryHeap { data: vec };
1454 #[stable(feature = "std_collections_from_array", since = "1.56.0")]
1455 impl<T: Ord, const N: usize> From<[T; N]> for BinaryHeap<T> {
1457 /// use std::collections::BinaryHeap;
1459 /// let mut h1 = BinaryHeap::from([1, 4, 2, 3]);
1460 /// let mut h2: BinaryHeap<_> = [1, 4, 2, 3].into();
1461 /// while let Some((a, b)) = h1.pop().zip(h2.pop()) {
1462 /// assert_eq!(a, b);
1465 fn from(arr: [T; N]) -> Self {
1466 core::array::IntoIter::new(arr).collect()
1470 #[stable(feature = "binary_heap_extras_15", since = "1.5.0")]
1471 impl<T> From<BinaryHeap<T>> for Vec<T> {
1472 /// Converts a `BinaryHeap<T>` into a `Vec<T>`.
1474 /// This conversion requires no data movement or allocation, and has
1475 /// constant time complexity.
1476 fn from(heap: BinaryHeap<T>) -> Vec<T> {
1481 #[stable(feature = "rust1", since = "1.0.0")]
1482 impl<T: Ord> FromIterator<T> for BinaryHeap<T> {
1483 fn from_iter<I: IntoIterator<Item = T>>(iter: I) -> BinaryHeap<T> {
1484 BinaryHeap::from(iter.into_iter().collect::<Vec<_>>())
1488 #[stable(feature = "rust1", since = "1.0.0")]
1489 impl<T> IntoIterator for BinaryHeap<T> {
1491 type IntoIter = IntoIter<T>;
1493 /// Creates a consuming iterator, that is, one that moves each value out of
1494 /// the binary heap in arbitrary order. The binary heap cannot be used
1495 /// after calling this.
1502 /// use std::collections::BinaryHeap;
1503 /// let heap = BinaryHeap::from(vec![1, 2, 3, 4]);
1505 /// // Print 1, 2, 3, 4 in arbitrary order
1506 /// for x in heap.into_iter() {
1507 /// // x has type i32, not &i32
1508 /// println!("{}", x);
1511 fn into_iter(self) -> IntoIter<T> {
1512 IntoIter { iter: self.data.into_iter() }
1516 #[stable(feature = "rust1", since = "1.0.0")]
1517 impl<'a, T> IntoIterator for &'a BinaryHeap<T> {
1519 type IntoIter = Iter<'a, T>;
1521 fn into_iter(self) -> Iter<'a, T> {
1526 #[stable(feature = "rust1", since = "1.0.0")]
1527 impl<T: Ord> Extend<T> for BinaryHeap<T> {
1529 fn extend<I: IntoIterator<Item = T>>(&mut self, iter: I) {
1530 <Self as SpecExtend<I>>::spec_extend(self, iter);
1534 fn extend_one(&mut self, item: T) {
1539 fn extend_reserve(&mut self, additional: usize) {
1540 self.reserve(additional);
1544 impl<T: Ord, I: IntoIterator<Item = T>> SpecExtend<I> for BinaryHeap<T> {
1545 default fn spec_extend(&mut self, iter: I) {
1546 self.extend_desugared(iter.into_iter());
1550 impl<T: Ord> SpecExtend<BinaryHeap<T>> for BinaryHeap<T> {
1551 fn spec_extend(&mut self, ref mut other: BinaryHeap<T>) {
1556 impl<T: Ord> BinaryHeap<T> {
1557 fn extend_desugared<I: IntoIterator<Item = T>>(&mut self, iter: I) {
1558 let iterator = iter.into_iter();
1559 let (lower, _) = iterator.size_hint();
1561 self.reserve(lower);
1563 iterator.for_each(move |elem| self.push(elem));
1567 #[stable(feature = "extend_ref", since = "1.2.0")]
1568 impl<'a, T: 'a + Ord + Copy> Extend<&'a T> for BinaryHeap<T> {
1569 fn extend<I: IntoIterator<Item = &'a T>>(&mut self, iter: I) {
1570 self.extend(iter.into_iter().cloned());
1574 fn extend_one(&mut self, &item: &'a T) {
1579 fn extend_reserve(&mut self, additional: usize) {
1580 self.reserve(additional);