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())
214 /// Either `std::cmp::Reverse` or a custom `Ord` implementation can be used to
215 /// make `BinaryHeap` a min-heap. This makes `heap.pop()` return the smallest
216 /// value instead of the greatest one.
219 /// use std::collections::BinaryHeap;
220 /// use std::cmp::Reverse;
222 /// let mut heap = BinaryHeap::new();
224 /// // Wrap values in `Reverse`
225 /// heap.push(Reverse(1));
226 /// heap.push(Reverse(5));
227 /// heap.push(Reverse(2));
229 /// // If we pop these scores now, they should come back in the reverse order.
230 /// assert_eq!(heap.pop(), Some(Reverse(1)));
231 /// assert_eq!(heap.pop(), Some(Reverse(2)));
232 /// assert_eq!(heap.pop(), Some(Reverse(5)));
233 /// assert_eq!(heap.pop(), None);
236 /// # Time complexity
238 /// | [push] | [pop] | [peek]/[peek\_mut] |
239 /// |--------|-----------|--------------------|
240 /// | O(1)~ | *O*(log(*n*)) | *O*(1) |
242 /// The value for `push` is an expected cost; the method documentation gives a
243 /// more detailed analysis.
245 /// [push]: BinaryHeap::push
246 /// [pop]: BinaryHeap::pop
247 /// [peek]: BinaryHeap::peek
248 /// [peek\_mut]: BinaryHeap::peek_mut
249 #[stable(feature = "rust1", since = "1.0.0")]
250 #[cfg_attr(not(test), rustc_diagnostic_item = "BinaryHeap")]
251 pub struct BinaryHeap<T> {
255 /// Structure wrapping a mutable reference to the greatest item on a
258 /// This `struct` is created by the [`peek_mut`] method on [`BinaryHeap`]. See
259 /// its documentation for more.
261 /// [`peek_mut`]: BinaryHeap::peek_mut
262 #[stable(feature = "binary_heap_peek_mut", since = "1.12.0")]
263 pub struct PeekMut<'a, T: 'a + Ord> {
264 heap: &'a mut BinaryHeap<T>,
268 #[stable(feature = "collection_debug", since = "1.17.0")]
269 impl<T: Ord + fmt::Debug> fmt::Debug for PeekMut<'_, T> {
270 fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
271 f.debug_tuple("PeekMut").field(&self.heap.data[0]).finish()
275 #[stable(feature = "binary_heap_peek_mut", since = "1.12.0")]
276 impl<T: Ord> Drop for PeekMut<'_, T> {
279 // SAFETY: PeekMut is only instantiated for non-empty heaps.
280 unsafe { self.heap.sift_down(0) };
285 #[stable(feature = "binary_heap_peek_mut", since = "1.12.0")]
286 impl<T: Ord> Deref for PeekMut<'_, T> {
288 fn deref(&self) -> &T {
289 debug_assert!(!self.heap.is_empty());
290 // SAFE: PeekMut is only instantiated for non-empty heaps
291 unsafe { self.heap.data.get_unchecked(0) }
295 #[stable(feature = "binary_heap_peek_mut", since = "1.12.0")]
296 impl<T: Ord> DerefMut for PeekMut<'_, T> {
297 fn deref_mut(&mut self) -> &mut T {
298 debug_assert!(!self.heap.is_empty());
300 // SAFE: PeekMut is only instantiated for non-empty heaps
301 unsafe { self.heap.data.get_unchecked_mut(0) }
305 impl<'a, T: Ord> PeekMut<'a, T> {
306 /// Removes the peeked value from the heap and returns it.
307 #[stable(feature = "binary_heap_peek_mut_pop", since = "1.18.0")]
308 pub fn pop(mut this: PeekMut<'a, T>) -> T {
309 let value = this.heap.pop().unwrap();
315 #[stable(feature = "rust1", since = "1.0.0")]
316 impl<T: Clone> Clone for BinaryHeap<T> {
317 fn clone(&self) -> Self {
318 BinaryHeap { data: self.data.clone() }
321 fn clone_from(&mut self, source: &Self) {
322 self.data.clone_from(&source.data);
326 #[stable(feature = "rust1", since = "1.0.0")]
327 impl<T: Ord> Default for BinaryHeap<T> {
328 /// Creates an empty `BinaryHeap<T>`.
330 fn default() -> BinaryHeap<T> {
335 #[stable(feature = "binaryheap_debug", since = "1.4.0")]
336 impl<T: fmt::Debug> fmt::Debug for BinaryHeap<T> {
337 fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
338 f.debug_list().entries(self.iter()).finish()
342 impl<T: Ord> BinaryHeap<T> {
343 /// Creates an empty `BinaryHeap` as a max-heap.
350 /// use std::collections::BinaryHeap;
351 /// let mut heap = BinaryHeap::new();
354 #[stable(feature = "rust1", since = "1.0.0")]
355 pub fn new() -> BinaryHeap<T> {
356 BinaryHeap { data: vec![] }
359 /// Creates an empty `BinaryHeap` with a specific capacity.
360 /// This preallocates enough memory for `capacity` elements,
361 /// so that the `BinaryHeap` does not have to be reallocated
362 /// until it contains at least that many values.
369 /// use std::collections::BinaryHeap;
370 /// let mut heap = BinaryHeap::with_capacity(10);
373 #[stable(feature = "rust1", since = "1.0.0")]
374 pub fn with_capacity(capacity: usize) -> BinaryHeap<T> {
375 BinaryHeap { data: Vec::with_capacity(capacity) }
378 /// Returns a mutable reference to the greatest item in the binary heap, or
379 /// `None` if it is empty.
381 /// Note: If the `PeekMut` value is leaked, the heap may be in an
382 /// inconsistent state.
389 /// use std::collections::BinaryHeap;
390 /// let mut heap = BinaryHeap::new();
391 /// assert!(heap.peek_mut().is_none());
397 /// let mut val = heap.peek_mut().unwrap();
400 /// assert_eq!(heap.peek(), Some(&2));
403 /// # Time complexity
405 /// If the item is modified then the worst case time complexity is *O*(log(*n*)),
406 /// otherwise it's *O*(1).
407 #[stable(feature = "binary_heap_peek_mut", since = "1.12.0")]
408 pub fn peek_mut(&mut self) -> Option<PeekMut<'_, T>> {
409 if self.is_empty() { None } else { Some(PeekMut { heap: self, sift: false }) }
412 /// Removes the greatest item from the binary heap and returns it, or `None` if it
420 /// use std::collections::BinaryHeap;
421 /// let mut heap = BinaryHeap::from(vec![1, 3]);
423 /// assert_eq!(heap.pop(), Some(3));
424 /// assert_eq!(heap.pop(), Some(1));
425 /// assert_eq!(heap.pop(), None);
428 /// # Time complexity
430 /// The worst case cost of `pop` on a heap containing *n* elements is *O*(log(*n*)).
431 #[stable(feature = "rust1", since = "1.0.0")]
432 pub fn pop(&mut self) -> Option<T> {
433 self.data.pop().map(|mut item| {
434 if !self.is_empty() {
435 swap(&mut item, &mut self.data[0]);
436 // SAFETY: !self.is_empty() means that self.len() > 0
437 unsafe { self.sift_down_to_bottom(0) };
443 /// Pushes an item onto the binary heap.
450 /// use std::collections::BinaryHeap;
451 /// let mut heap = BinaryHeap::new();
456 /// assert_eq!(heap.len(), 3);
457 /// assert_eq!(heap.peek(), Some(&5));
460 /// # Time complexity
462 /// The expected cost of `push`, averaged over every possible ordering of
463 /// the elements being pushed, and over a sufficiently large number of
464 /// pushes, is *O*(1). This is the most meaningful cost metric when pushing
465 /// elements that are *not* already in any sorted pattern.
467 /// The time complexity degrades if elements are pushed in predominantly
468 /// ascending order. In the worst case, elements are pushed in ascending
469 /// sorted order and the amortized cost per push is *O*(log(*n*)) against a heap
470 /// containing *n* elements.
472 /// The worst case cost of a *single* call to `push` is *O*(*n*). The worst case
473 /// occurs when capacity is exhausted and needs a resize. The resize cost
474 /// has been amortized in the previous figures.
475 #[stable(feature = "rust1", since = "1.0.0")]
476 pub fn push(&mut self, item: T) {
477 let old_len = self.len();
478 self.data.push(item);
479 // SAFETY: Since we pushed a new item it means that
480 // old_len = self.len() - 1 < self.len()
481 unsafe { self.sift_up(0, old_len) };
484 /// Consumes the `BinaryHeap` and returns a vector in sorted
485 /// (ascending) order.
492 /// use std::collections::BinaryHeap;
494 /// let mut heap = BinaryHeap::from(vec![1, 2, 4, 5, 7]);
498 /// let vec = heap.into_sorted_vec();
499 /// assert_eq!(vec, [1, 2, 3, 4, 5, 6, 7]);
501 #[stable(feature = "binary_heap_extras_15", since = "1.5.0")]
502 pub fn into_sorted_vec(mut self) -> Vec<T> {
503 let mut end = self.len();
506 // SAFETY: `end` goes from `self.len() - 1` to 1 (both included),
507 // so it's always a valid index to access.
508 // It is safe to access index 0 (i.e. `ptr`), because
509 // 1 <= end < self.len(), which means self.len() >= 2.
511 let ptr = self.data.as_mut_ptr();
512 ptr::swap(ptr, ptr.add(end));
514 // SAFETY: `end` goes from `self.len() - 1` to 1 (both included) so:
515 // 0 < 1 <= end <= self.len() - 1 < self.len()
516 // Which means 0 < end and end < self.len().
517 unsafe { self.sift_down_range(0, end) };
522 // The implementations of sift_up and sift_down use unsafe blocks in
523 // order to move an element out of the vector (leaving behind a
524 // hole), shift along the others and move the removed element back into the
525 // vector at the final location of the hole.
526 // The `Hole` type is used to represent this, and make sure
527 // the hole is filled back at the end of its scope, even on panic.
528 // Using a hole reduces the constant factor compared to using swaps,
529 // which involves twice as many moves.
533 /// The caller must guarantee that `pos < self.len()`.
534 unsafe fn sift_up(&mut self, start: usize, pos: usize) -> usize {
535 // Take out the value at `pos` and create a hole.
536 // SAFETY: The caller guarantees that pos < self.len()
537 let mut hole = unsafe { Hole::new(&mut self.data, pos) };
539 while hole.pos() > start {
540 let parent = (hole.pos() - 1) / 2;
542 // SAFETY: hole.pos() > start >= 0, which means hole.pos() > 0
543 // and so hole.pos() - 1 can't underflow.
544 // This guarantees that parent < hole.pos() so
545 // it's a valid index and also != hole.pos().
546 if hole.element() <= unsafe { hole.get(parent) } {
550 // SAFETY: Same as above
551 unsafe { hole.move_to(parent) };
557 /// Take an element at `pos` and move it down the heap,
558 /// while its children are larger.
562 /// The caller must guarantee that `pos < end <= self.len()`.
563 unsafe fn sift_down_range(&mut self, pos: usize, end: usize) {
564 // SAFETY: The caller guarantees that pos < end <= self.len().
565 let mut hole = unsafe { Hole::new(&mut self.data, pos) };
566 let mut child = 2 * hole.pos() + 1;
568 // Loop invariant: child == 2 * hole.pos() + 1.
569 while child <= end.saturating_sub(2) {
570 // compare with the greater of the two children
571 // SAFETY: child < end - 1 < self.len() and
572 // child + 1 < end <= self.len(), so they're valid indexes.
573 // child == 2 * hole.pos() + 1 != hole.pos() and
574 // child + 1 == 2 * hole.pos() + 2 != hole.pos().
575 // FIXME: 2 * hole.pos() + 1 or 2 * hole.pos() + 2 could overflow
577 child += unsafe { hole.get(child) <= hole.get(child + 1) } as usize;
579 // if we are already in order, stop.
580 // SAFETY: child is now either the old child or the old child+1
581 // We already proven that both are < self.len() and != hole.pos()
582 if hole.element() >= unsafe { hole.get(child) } {
586 // SAFETY: same as above.
587 unsafe { hole.move_to(child) };
588 child = 2 * hole.pos() + 1;
591 // SAFETY: && short circuit, which means that in the
592 // second condition it's already true that child == end - 1 < self.len().
593 if child == end - 1 && hole.element() < unsafe { hole.get(child) } {
594 // SAFETY: child is already proven to be a valid index and
595 // child == 2 * hole.pos() + 1 != hole.pos().
596 unsafe { hole.move_to(child) };
602 /// The caller must guarantee that `pos < self.len()`.
603 unsafe fn sift_down(&mut self, pos: usize) {
604 let len = self.len();
605 // SAFETY: pos < len is guaranteed by the caller and
606 // obviously len = self.len() <= self.len().
607 unsafe { self.sift_down_range(pos, len) };
610 /// Take an element at `pos` and move it all the way down the heap,
611 /// then sift it up to its position.
613 /// Note: This is faster when the element is known to be large / should
614 /// be closer to the bottom.
618 /// The caller must guarantee that `pos < self.len()`.
619 unsafe fn sift_down_to_bottom(&mut self, mut pos: usize) {
620 let end = self.len();
623 // SAFETY: The caller guarantees that pos < self.len().
624 let mut hole = unsafe { Hole::new(&mut self.data, pos) };
625 let mut child = 2 * hole.pos() + 1;
627 // Loop invariant: child == 2 * hole.pos() + 1.
628 while child <= end.saturating_sub(2) {
629 // SAFETY: child < end - 1 < self.len() and
630 // child + 1 < end <= self.len(), so they're valid indexes.
631 // child == 2 * hole.pos() + 1 != hole.pos() and
632 // child + 1 == 2 * hole.pos() + 2 != hole.pos().
633 // FIXME: 2 * hole.pos() + 1 or 2 * hole.pos() + 2 could overflow
635 child += unsafe { hole.get(child) <= hole.get(child + 1) } as usize;
637 // SAFETY: Same as above
638 unsafe { hole.move_to(child) };
639 child = 2 * hole.pos() + 1;
642 if child == end - 1 {
643 // SAFETY: child == end - 1 < self.len(), so it's a valid index
644 // and child == 2 * hole.pos() + 1 != hole.pos().
645 unsafe { hole.move_to(child) };
650 // SAFETY: pos is the position in the hole and was already proven
651 // to be a valid index.
652 unsafe { self.sift_up(start, pos) };
655 fn rebuild(&mut self) {
656 let mut n = self.len() / 2;
659 // SAFETY: n starts from self.len() / 2 and goes down to 0.
660 // The only case when !(n < self.len()) is if
661 // self.len() == 0, but it's ruled out by the loop condition.
662 unsafe { self.sift_down(n) };
666 /// Moves all the elements of `other` into `self`, leaving `other` empty.
673 /// use std::collections::BinaryHeap;
675 /// let v = vec![-10, 1, 2, 3, 3];
676 /// let mut a = BinaryHeap::from(v);
678 /// let v = vec![-20, 5, 43];
679 /// let mut b = BinaryHeap::from(v);
681 /// a.append(&mut b);
683 /// assert_eq!(a.into_sorted_vec(), [-20, -10, 1, 2, 3, 3, 5, 43]);
684 /// assert!(b.is_empty());
686 #[stable(feature = "binary_heap_append", since = "1.11.0")]
687 pub fn append(&mut self, other: &mut Self) {
688 if self.len() < other.len() {
692 if other.is_empty() {
697 fn log2_fast(x: usize) -> usize {
698 (usize::BITS - x.leading_zeros() - 1) as usize
701 // `rebuild` takes O(len1 + len2) operations
702 // and about 2 * (len1 + len2) comparisons in the worst case
703 // while `extend` takes O(len2 * log(len1)) operations
704 // and about 1 * len2 * log_2(len1) comparisons in the worst case,
705 // assuming len1 >= len2. For larger heaps, the crossover point
706 // no longer follows this reasoning and was determined empirically.
708 fn better_to_rebuild(len1: usize, len2: usize) -> bool {
709 let tot_len = len1 + len2;
711 2 * tot_len < len2 * log2_fast(len1)
713 2 * tot_len < len2 * 11
717 if better_to_rebuild(self.len(), other.len()) {
718 self.data.append(&mut other.data);
721 self.extend(other.drain());
725 /// Returns an iterator which retrieves elements in heap order.
726 /// The retrieved elements are removed from the original heap.
727 /// The remaining elements will be removed on drop in heap order.
730 /// * `.drain_sorted()` is *O*(*n* \* log(*n*)); much slower than `.drain()`.
731 /// You should use the latter for most cases.
738 /// #![feature(binary_heap_drain_sorted)]
739 /// use std::collections::BinaryHeap;
741 /// let mut heap = BinaryHeap::from(vec![1, 2, 3, 4, 5]);
742 /// assert_eq!(heap.len(), 5);
744 /// drop(heap.drain_sorted()); // removes all elements in heap order
745 /// assert_eq!(heap.len(), 0);
748 #[unstable(feature = "binary_heap_drain_sorted", issue = "59278")]
749 pub fn drain_sorted(&mut self) -> DrainSorted<'_, T> {
750 DrainSorted { inner: self }
753 /// Retains only the elements specified by the predicate.
755 /// In other words, remove all elements `e` such that `f(&e)` returns
756 /// `false`. The elements are visited in unsorted (and unspecified) order.
763 /// #![feature(binary_heap_retain)]
764 /// use std::collections::BinaryHeap;
766 /// let mut heap = BinaryHeap::from(vec![-10, -5, 1, 2, 4, 13]);
768 /// heap.retain(|x| x % 2 == 0); // only keep even numbers
770 /// assert_eq!(heap.into_sorted_vec(), [-10, 2, 4])
772 #[unstable(feature = "binary_heap_retain", issue = "71503")]
773 pub fn retain<F>(&mut self, f: F)
775 F: FnMut(&T) -> bool,
782 impl<T> BinaryHeap<T> {
783 /// Returns an iterator visiting all values in the underlying vector, in
791 /// use std::collections::BinaryHeap;
792 /// let heap = BinaryHeap::from(vec![1, 2, 3, 4]);
794 /// // Print 1, 2, 3, 4 in arbitrary order
795 /// for x in heap.iter() {
796 /// println!("{}", x);
799 #[stable(feature = "rust1", since = "1.0.0")]
800 pub fn iter(&self) -> Iter<'_, T> {
801 Iter { iter: self.data.iter() }
804 /// Returns an iterator which retrieves elements in heap order.
805 /// This method consumes the original heap.
812 /// #![feature(binary_heap_into_iter_sorted)]
813 /// use std::collections::BinaryHeap;
814 /// let heap = BinaryHeap::from(vec![1, 2, 3, 4, 5]);
816 /// assert_eq!(heap.into_iter_sorted().take(2).collect::<Vec<_>>(), vec![5, 4]);
818 #[unstable(feature = "binary_heap_into_iter_sorted", issue = "59278")]
819 pub fn into_iter_sorted(self) -> IntoIterSorted<T> {
820 IntoIterSorted { inner: self }
823 /// Returns the greatest item in the binary heap, or `None` if it is empty.
830 /// use std::collections::BinaryHeap;
831 /// let mut heap = BinaryHeap::new();
832 /// assert_eq!(heap.peek(), None);
837 /// assert_eq!(heap.peek(), Some(&5));
841 /// # Time complexity
843 /// Cost is *O*(1) in the worst case.
844 #[stable(feature = "rust1", since = "1.0.0")]
845 pub fn peek(&self) -> Option<&T> {
849 /// Returns the number of elements the binary heap can hold without reallocating.
856 /// use std::collections::BinaryHeap;
857 /// let mut heap = BinaryHeap::with_capacity(100);
858 /// assert!(heap.capacity() >= 100);
861 #[stable(feature = "rust1", since = "1.0.0")]
862 pub fn capacity(&self) -> usize {
866 /// Reserves the minimum capacity for exactly `additional` more elements to be inserted in the
867 /// given `BinaryHeap`. Does nothing if the capacity is already sufficient.
869 /// Note that the allocator may give the collection more space than it requests. Therefore
870 /// capacity can not be relied upon to be precisely minimal. Prefer [`reserve`] if future
871 /// insertions are expected.
875 /// Panics if the new capacity overflows `usize`.
882 /// use std::collections::BinaryHeap;
883 /// let mut heap = BinaryHeap::new();
884 /// heap.reserve_exact(100);
885 /// assert!(heap.capacity() >= 100);
889 /// [`reserve`]: BinaryHeap::reserve
890 #[stable(feature = "rust1", since = "1.0.0")]
891 pub fn reserve_exact(&mut self, additional: usize) {
892 self.data.reserve_exact(additional);
895 /// Reserves capacity for at least `additional` more elements to be inserted in the
896 /// `BinaryHeap`. The collection may reserve more space to avoid frequent reallocations.
900 /// Panics if the new capacity overflows `usize`.
907 /// use std::collections::BinaryHeap;
908 /// let mut heap = BinaryHeap::new();
909 /// heap.reserve(100);
910 /// assert!(heap.capacity() >= 100);
913 #[stable(feature = "rust1", since = "1.0.0")]
914 pub fn reserve(&mut self, additional: usize) {
915 self.data.reserve(additional);
918 /// Discards as much additional capacity as possible.
925 /// use std::collections::BinaryHeap;
926 /// let mut heap: BinaryHeap<i32> = BinaryHeap::with_capacity(100);
928 /// assert!(heap.capacity() >= 100);
929 /// heap.shrink_to_fit();
930 /// assert!(heap.capacity() == 0);
932 #[stable(feature = "rust1", since = "1.0.0")]
933 pub fn shrink_to_fit(&mut self) {
934 self.data.shrink_to_fit();
937 /// Discards capacity with a lower bound.
939 /// The capacity will remain at least as large as both the length
940 /// and the supplied value.
942 /// If the current capacity is less than the lower limit, this is a no-op.
947 /// #![feature(shrink_to)]
948 /// use std::collections::BinaryHeap;
949 /// let mut heap: BinaryHeap<i32> = BinaryHeap::with_capacity(100);
951 /// assert!(heap.capacity() >= 100);
952 /// heap.shrink_to(10);
953 /// assert!(heap.capacity() >= 10);
956 #[unstable(feature = "shrink_to", reason = "new API", issue = "56431")]
957 pub fn shrink_to(&mut self, min_capacity: usize) {
958 self.data.shrink_to(min_capacity)
961 /// Returns a slice of all values in the underlying vector, in arbitrary
969 /// #![feature(binary_heap_as_slice)]
970 /// use std::collections::BinaryHeap;
971 /// use std::io::{self, Write};
973 /// let heap = BinaryHeap::from(vec![1, 2, 3, 4, 5, 6, 7]);
975 /// io::sink().write(heap.as_slice()).unwrap();
977 #[unstable(feature = "binary_heap_as_slice", issue = "83659")]
978 pub fn as_slice(&self) -> &[T] {
982 /// Consumes the `BinaryHeap` and returns the underlying vector
983 /// in arbitrary order.
990 /// use std::collections::BinaryHeap;
991 /// let heap = BinaryHeap::from(vec![1, 2, 3, 4, 5, 6, 7]);
992 /// let vec = heap.into_vec();
994 /// // Will print in some order
996 /// println!("{}", x);
999 #[stable(feature = "binary_heap_extras_15", since = "1.5.0")]
1000 pub fn into_vec(self) -> Vec<T> {
1004 /// Returns the length of the binary heap.
1011 /// use std::collections::BinaryHeap;
1012 /// let heap = BinaryHeap::from(vec![1, 3]);
1014 /// assert_eq!(heap.len(), 2);
1016 #[doc(alias = "length")]
1017 #[stable(feature = "rust1", since = "1.0.0")]
1018 pub fn len(&self) -> usize {
1022 /// Checks if the binary heap is empty.
1029 /// use std::collections::BinaryHeap;
1030 /// let mut heap = BinaryHeap::new();
1032 /// assert!(heap.is_empty());
1038 /// assert!(!heap.is_empty());
1040 #[stable(feature = "rust1", since = "1.0.0")]
1041 pub fn is_empty(&self) -> bool {
1045 /// Clears the binary heap, returning an iterator over the removed elements.
1047 /// The elements are removed in arbitrary order.
1054 /// use std::collections::BinaryHeap;
1055 /// let mut heap = BinaryHeap::from(vec![1, 3]);
1057 /// assert!(!heap.is_empty());
1059 /// for x in heap.drain() {
1060 /// println!("{}", x);
1063 /// assert!(heap.is_empty());
1066 #[stable(feature = "drain", since = "1.6.0")]
1067 pub fn drain(&mut self) -> Drain<'_, T> {
1068 Drain { iter: self.data.drain(..) }
1071 /// Drops all items from the binary heap.
1078 /// use std::collections::BinaryHeap;
1079 /// let mut heap = BinaryHeap::from(vec![1, 3]);
1081 /// assert!(!heap.is_empty());
1085 /// assert!(heap.is_empty());
1087 #[stable(feature = "rust1", since = "1.0.0")]
1088 pub fn clear(&mut self) {
1093 /// Hole represents a hole in a slice i.e., an index without valid value
1094 /// (because it was moved from or duplicated).
1095 /// In drop, `Hole` will restore the slice by filling the hole
1096 /// position with the value that was originally removed.
1097 struct Hole<'a, T: 'a> {
1099 elt: ManuallyDrop<T>,
1103 impl<'a, T> Hole<'a, T> {
1104 /// Create a new `Hole` at index `pos`.
1106 /// Unsafe because pos must be within the data slice.
1108 unsafe fn new(data: &'a mut [T], pos: usize) -> Self {
1109 debug_assert!(pos < data.len());
1110 // SAFE: pos should be inside the slice
1111 let elt = unsafe { ptr::read(data.get_unchecked(pos)) };
1112 Hole { data, elt: ManuallyDrop::new(elt), pos }
1116 fn pos(&self) -> usize {
1120 /// Returns a reference to the element removed.
1122 fn element(&self) -> &T {
1126 /// Returns a reference to the element at `index`.
1128 /// Unsafe because index must be within the data slice and not equal to pos.
1130 unsafe fn get(&self, index: usize) -> &T {
1131 debug_assert!(index != self.pos);
1132 debug_assert!(index < self.data.len());
1133 unsafe { self.data.get_unchecked(index) }
1136 /// Move hole to new location
1138 /// Unsafe because index must be within the data slice and not equal to pos.
1140 unsafe fn move_to(&mut self, index: usize) {
1141 debug_assert!(index != self.pos);
1142 debug_assert!(index < self.data.len());
1144 let ptr = self.data.as_mut_ptr();
1145 let index_ptr: *const _ = ptr.add(index);
1146 let hole_ptr = ptr.add(self.pos);
1147 ptr::copy_nonoverlapping(index_ptr, hole_ptr, 1);
1153 impl<T> Drop for Hole<'_, T> {
1155 fn drop(&mut self) {
1156 // fill the hole again
1159 ptr::copy_nonoverlapping(&*self.elt, self.data.get_unchecked_mut(pos), 1);
1164 /// An iterator over the elements of a `BinaryHeap`.
1166 /// This `struct` is created by [`BinaryHeap::iter()`]. See its
1167 /// documentation for more.
1169 /// [`iter`]: BinaryHeap::iter
1170 #[stable(feature = "rust1", since = "1.0.0")]
1171 pub struct Iter<'a, T: 'a> {
1172 iter: slice::Iter<'a, T>,
1175 #[stable(feature = "collection_debug", since = "1.17.0")]
1176 impl<T: fmt::Debug> fmt::Debug for Iter<'_, T> {
1177 fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
1178 f.debug_tuple("Iter").field(&self.iter.as_slice()).finish()
1182 // FIXME(#26925) Remove in favor of `#[derive(Clone)]`
1183 #[stable(feature = "rust1", since = "1.0.0")]
1184 impl<T> Clone for Iter<'_, T> {
1185 fn clone(&self) -> Self {
1186 Iter { iter: self.iter.clone() }
1190 #[stable(feature = "rust1", since = "1.0.0")]
1191 impl<'a, T> Iterator for Iter<'a, T> {
1195 fn next(&mut self) -> Option<&'a T> {
1200 fn size_hint(&self) -> (usize, Option<usize>) {
1201 self.iter.size_hint()
1205 fn last(self) -> Option<&'a T> {
1210 #[stable(feature = "rust1", since = "1.0.0")]
1211 impl<'a, T> DoubleEndedIterator for Iter<'a, T> {
1213 fn next_back(&mut self) -> Option<&'a T> {
1214 self.iter.next_back()
1218 #[stable(feature = "rust1", since = "1.0.0")]
1219 impl<T> ExactSizeIterator for Iter<'_, T> {
1220 fn is_empty(&self) -> bool {
1221 self.iter.is_empty()
1225 #[stable(feature = "fused", since = "1.26.0")]
1226 impl<T> FusedIterator for Iter<'_, T> {}
1228 /// An owning iterator over the elements of a `BinaryHeap`.
1230 /// This `struct` is created by [`BinaryHeap::into_iter()`]
1231 /// (provided by the `IntoIterator` trait). See its documentation for more.
1233 /// [`into_iter`]: BinaryHeap::into_iter
1234 #[stable(feature = "rust1", since = "1.0.0")]
1236 pub struct IntoIter<T> {
1237 iter: vec::IntoIter<T>,
1240 #[stable(feature = "collection_debug", since = "1.17.0")]
1241 impl<T: fmt::Debug> fmt::Debug for IntoIter<T> {
1242 fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
1243 f.debug_tuple("IntoIter").field(&self.iter.as_slice()).finish()
1247 #[stable(feature = "rust1", since = "1.0.0")]
1248 impl<T> Iterator for IntoIter<T> {
1252 fn next(&mut self) -> Option<T> {
1257 fn size_hint(&self) -> (usize, Option<usize>) {
1258 self.iter.size_hint()
1262 #[stable(feature = "rust1", since = "1.0.0")]
1263 impl<T> DoubleEndedIterator for IntoIter<T> {
1265 fn next_back(&mut self) -> Option<T> {
1266 self.iter.next_back()
1270 #[stable(feature = "rust1", since = "1.0.0")]
1271 impl<T> ExactSizeIterator for IntoIter<T> {
1272 fn is_empty(&self) -> bool {
1273 self.iter.is_empty()
1277 #[stable(feature = "fused", since = "1.26.0")]
1278 impl<T> FusedIterator for IntoIter<T> {}
1280 #[unstable(issue = "none", feature = "inplace_iteration")]
1281 unsafe impl<T> SourceIter for IntoIter<T> {
1282 type Source = IntoIter<T>;
1285 unsafe fn as_inner(&mut self) -> &mut Self::Source {
1290 #[unstable(issue = "none", feature = "inplace_iteration")]
1291 unsafe impl<I> InPlaceIterable for IntoIter<I> {}
1293 impl<I> AsIntoIter for IntoIter<I> {
1296 fn as_into_iter(&mut self) -> &mut vec::IntoIter<Self::Item> {
1301 #[unstable(feature = "binary_heap_into_iter_sorted", issue = "59278")]
1302 #[derive(Clone, Debug)]
1303 pub struct IntoIterSorted<T> {
1304 inner: BinaryHeap<T>,
1307 #[unstable(feature = "binary_heap_into_iter_sorted", issue = "59278")]
1308 impl<T: Ord> Iterator for IntoIterSorted<T> {
1312 fn next(&mut self) -> Option<T> {
1317 fn size_hint(&self) -> (usize, Option<usize>) {
1318 let exact = self.inner.len();
1319 (exact, Some(exact))
1323 #[unstable(feature = "binary_heap_into_iter_sorted", issue = "59278")]
1324 impl<T: Ord> ExactSizeIterator for IntoIterSorted<T> {}
1326 #[unstable(feature = "binary_heap_into_iter_sorted", issue = "59278")]
1327 impl<T: Ord> FusedIterator for IntoIterSorted<T> {}
1329 #[unstable(feature = "trusted_len", issue = "37572")]
1330 unsafe impl<T: Ord> TrustedLen for IntoIterSorted<T> {}
1332 /// A draining iterator over the elements of a `BinaryHeap`.
1334 /// This `struct` is created by [`BinaryHeap::drain()`]. See its
1335 /// documentation for more.
1337 /// [`drain`]: BinaryHeap::drain
1338 #[stable(feature = "drain", since = "1.6.0")]
1340 pub struct Drain<'a, T: 'a> {
1341 iter: vec::Drain<'a, T>,
1344 #[stable(feature = "drain", since = "1.6.0")]
1345 impl<T> Iterator for Drain<'_, T> {
1349 fn next(&mut self) -> Option<T> {
1354 fn size_hint(&self) -> (usize, Option<usize>) {
1355 self.iter.size_hint()
1359 #[stable(feature = "drain", since = "1.6.0")]
1360 impl<T> DoubleEndedIterator for Drain<'_, T> {
1362 fn next_back(&mut self) -> Option<T> {
1363 self.iter.next_back()
1367 #[stable(feature = "drain", since = "1.6.0")]
1368 impl<T> ExactSizeIterator for Drain<'_, T> {
1369 fn is_empty(&self) -> bool {
1370 self.iter.is_empty()
1374 #[stable(feature = "fused", since = "1.26.0")]
1375 impl<T> FusedIterator for Drain<'_, T> {}
1377 /// A draining iterator over the elements of a `BinaryHeap`.
1379 /// This `struct` is created by [`BinaryHeap::drain_sorted()`]. See its
1380 /// documentation for more.
1382 /// [`drain_sorted`]: BinaryHeap::drain_sorted
1383 #[unstable(feature = "binary_heap_drain_sorted", issue = "59278")]
1385 pub struct DrainSorted<'a, T: Ord> {
1386 inner: &'a mut BinaryHeap<T>,
1389 #[unstable(feature = "binary_heap_drain_sorted", issue = "59278")]
1390 impl<'a, T: Ord> Drop for DrainSorted<'a, T> {
1391 /// Removes heap elements in heap order.
1392 fn drop(&mut self) {
1393 struct DropGuard<'r, 'a, T: Ord>(&'r mut DrainSorted<'a, T>);
1395 impl<'r, 'a, T: Ord> Drop for DropGuard<'r, 'a, T> {
1396 fn drop(&mut self) {
1397 while self.0.inner.pop().is_some() {}
1401 while let Some(item) = self.inner.pop() {
1402 let guard = DropGuard(self);
1409 #[unstable(feature = "binary_heap_drain_sorted", issue = "59278")]
1410 impl<T: Ord> Iterator for DrainSorted<'_, T> {
1414 fn next(&mut self) -> Option<T> {
1419 fn size_hint(&self) -> (usize, Option<usize>) {
1420 let exact = self.inner.len();
1421 (exact, Some(exact))
1425 #[unstable(feature = "binary_heap_drain_sorted", issue = "59278")]
1426 impl<T: Ord> ExactSizeIterator for DrainSorted<'_, T> {}
1428 #[unstable(feature = "binary_heap_drain_sorted", issue = "59278")]
1429 impl<T: Ord> FusedIterator for DrainSorted<'_, T> {}
1431 #[unstable(feature = "trusted_len", issue = "37572")]
1432 unsafe impl<T: Ord> TrustedLen for DrainSorted<'_, T> {}
1434 #[stable(feature = "binary_heap_extras_15", since = "1.5.0")]
1435 impl<T: Ord> From<Vec<T>> for BinaryHeap<T> {
1436 /// Converts a `Vec<T>` into a `BinaryHeap<T>`.
1438 /// This conversion happens in-place, and has *O*(*n*) time complexity.
1439 fn from(vec: Vec<T>) -> BinaryHeap<T> {
1440 let mut heap = BinaryHeap { data: vec };
1446 #[stable(feature = "binary_heap_extras_15", since = "1.5.0")]
1447 impl<T> From<BinaryHeap<T>> for Vec<T> {
1448 /// Converts a `BinaryHeap<T>` into a `Vec<T>`.
1450 /// This conversion requires no data movement or allocation, and has
1451 /// constant time complexity.
1452 fn from(heap: BinaryHeap<T>) -> Vec<T> {
1457 #[stable(feature = "rust1", since = "1.0.0")]
1458 impl<T: Ord> FromIterator<T> for BinaryHeap<T> {
1459 fn from_iter<I: IntoIterator<Item = T>>(iter: I) -> BinaryHeap<T> {
1460 BinaryHeap::from(iter.into_iter().collect::<Vec<_>>())
1464 #[stable(feature = "rust1", since = "1.0.0")]
1465 impl<T> IntoIterator for BinaryHeap<T> {
1467 type IntoIter = IntoIter<T>;
1469 /// Creates a consuming iterator, that is, one that moves each value out of
1470 /// the binary heap in arbitrary order. The binary heap cannot be used
1471 /// after calling this.
1478 /// use std::collections::BinaryHeap;
1479 /// let heap = BinaryHeap::from(vec![1, 2, 3, 4]);
1481 /// // Print 1, 2, 3, 4 in arbitrary order
1482 /// for x in heap.into_iter() {
1483 /// // x has type i32, not &i32
1484 /// println!("{}", x);
1487 fn into_iter(self) -> IntoIter<T> {
1488 IntoIter { iter: self.data.into_iter() }
1492 #[stable(feature = "rust1", since = "1.0.0")]
1493 impl<'a, T> IntoIterator for &'a BinaryHeap<T> {
1495 type IntoIter = Iter<'a, T>;
1497 fn into_iter(self) -> Iter<'a, T> {
1502 #[stable(feature = "rust1", since = "1.0.0")]
1503 impl<T: Ord> Extend<T> for BinaryHeap<T> {
1505 fn extend<I: IntoIterator<Item = T>>(&mut self, iter: I) {
1506 <Self as SpecExtend<I>>::spec_extend(self, iter);
1510 fn extend_one(&mut self, item: T) {
1515 fn extend_reserve(&mut self, additional: usize) {
1516 self.reserve(additional);
1520 impl<T: Ord, I: IntoIterator<Item = T>> SpecExtend<I> for BinaryHeap<T> {
1521 default fn spec_extend(&mut self, iter: I) {
1522 self.extend_desugared(iter.into_iter());
1526 impl<T: Ord> SpecExtend<BinaryHeap<T>> for BinaryHeap<T> {
1527 fn spec_extend(&mut self, ref mut other: BinaryHeap<T>) {
1532 impl<T: Ord> BinaryHeap<T> {
1533 fn extend_desugared<I: IntoIterator<Item = T>>(&mut self, iter: I) {
1534 let iterator = iter.into_iter();
1535 let (lower, _) = iterator.size_hint();
1537 self.reserve(lower);
1539 iterator.for_each(move |elem| self.push(elem));
1543 #[stable(feature = "extend_ref", since = "1.2.0")]
1544 impl<'a, T: 'a + Ord + Copy> Extend<&'a T> for BinaryHeap<T> {
1545 fn extend<I: IntoIterator<Item = &'a T>>(&mut self, iter: I) {
1546 self.extend(iter.into_iter().cloned());
1550 fn extend_one(&mut self, &item: &'a T) {
1555 fn extend_reserve(&mut self, additional: usize) {
1556 self.reserve(additional);