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
18 //! [`BinaryHeap`]: struct.BinaryHeap.html
21 //! use std::cmp::Ordering;
22 //! use std::collections::BinaryHeap;
24 //! #[derive(Copy, Clone, Eq, PartialEq)]
30 //! // The priority queue depends on `Ord`.
31 //! // Explicitly implement the trait so the queue becomes a min-heap
32 //! // instead of a max-heap.
33 //! impl Ord for State {
34 //! fn cmp(&self, other: &State) -> Ordering {
35 //! // Notice that the we flip the ordering on costs.
36 //! // In case of a tie we compare positions - this step is necessary
37 //! // to make implementations of `PartialEq` and `Ord` consistent.
38 //! other.cost.cmp(&self.cost)
39 //! .then_with(|| self.position.cmp(&other.position))
43 //! // `PartialOrd` needs to be implemented as well.
44 //! impl PartialOrd for State {
45 //! fn partial_cmp(&self, other: &State) -> Option<Ordering> {
46 //! Some(self.cmp(other))
50 //! // Each node is represented as an `usize`, for a shorter implementation.
56 //! // Dijkstra's shortest path algorithm.
58 //! // Start at `start` and use `dist` to track the current shortest distance
59 //! // to each node. This implementation isn't memory-efficient as it may leave duplicate
60 //! // nodes in the queue. It also uses `usize::MAX` as a sentinel value,
61 //! // for a simpler implementation.
62 //! fn shortest_path(adj_list: &Vec<Vec<Edge>>, start: usize, goal: usize) -> Option<usize> {
63 //! // dist[node] = current shortest distance from `start` to `node`
64 //! let mut dist: Vec<_> = (0..adj_list.len()).map(|_| usize::MAX).collect();
66 //! let mut heap = BinaryHeap::new();
68 //! // We're at `start`, with a zero cost
70 //! heap.push(State { cost: 0, position: start });
72 //! // Examine the frontier with lower cost nodes first (min-heap)
73 //! while let Some(State { cost, position }) = heap.pop() {
74 //! // Alternatively we could have continued to find all shortest paths
75 //! if position == goal { return Some(cost); }
77 //! // Important as we may have already found a better way
78 //! if cost > dist[position] { continue; }
80 //! // For each node we can reach, see if we can find a way with
81 //! // a lower cost going through this node
82 //! for edge in &adj_list[position] {
83 //! let next = State { cost: cost + edge.cost, position: edge.node };
85 //! // If so, add it to the frontier and continue
86 //! if next.cost < dist[next.position] {
88 //! // Relaxation, we have now found a better way
89 //! dist[next.position] = next.cost;
94 //! // Goal not reachable
99 //! // This is the directed graph we're going to use.
100 //! // The node numbers correspond to the different states,
101 //! // and the edge weights symbolize the cost of moving
102 //! // from one node to another.
103 //! // Note that the edges are one-way.
106 //! // +-----------------+
109 //! // 0 -----> 1 -----> 3 ---> 4
113 //! // +------> 2 -------+ |
115 //! // +---------------+
117 //! // The graph is represented as an adjacency list where each index,
118 //! // corresponding to a node value, has a list of outgoing edges.
119 //! // Chosen for its efficiency.
120 //! let graph = vec![
122 //! vec![Edge { node: 2, cost: 10 },
123 //! Edge { node: 1, cost: 1 }],
125 //! vec![Edge { node: 3, cost: 2 }],
127 //! vec![Edge { node: 1, cost: 1 },
128 //! Edge { node: 3, cost: 3 },
129 //! Edge { node: 4, cost: 1 }],
131 //! vec![Edge { node: 0, cost: 7 },
132 //! Edge { node: 4, cost: 2 }],
136 //! assert_eq!(shortest_path(&graph, 0, 1), Some(1));
137 //! assert_eq!(shortest_path(&graph, 0, 3), Some(3));
138 //! assert_eq!(shortest_path(&graph, 3, 0), Some(7));
139 //! assert_eq!(shortest_path(&graph, 0, 4), Some(5));
140 //! assert_eq!(shortest_path(&graph, 4, 0), None);
144 #![allow(missing_docs)]
145 #![stable(feature = "rust1", since = "1.0.0")]
148 use core::iter::{FromIterator, FusedIterator, InPlaceIterable, SourceIter, TrustedLen};
149 use core::mem::{self, size_of, swap, ManuallyDrop};
150 use core::ops::{Deref, DerefMut};
154 use crate::vec::{self, AsIntoIter, Vec};
156 use super::SpecExtend;
158 /// A priority queue implemented with a binary heap.
160 /// This will be a max-heap.
162 /// It is a logic error for an item to be modified in such a way that the
163 /// item's ordering relative to any other item, as determined by the `Ord`
164 /// trait, changes while it is in the heap. This is normally only possible
165 /// through `Cell`, `RefCell`, global state, I/O, or unsafe code.
170 /// use std::collections::BinaryHeap;
172 /// // Type inference lets us omit an explicit type signature (which
173 /// // would be `BinaryHeap<i32>` in this example).
174 /// let mut heap = BinaryHeap::new();
176 /// // We can use peek to look at the next item in the heap. In this case,
177 /// // there's no items in there yet so we get None.
178 /// assert_eq!(heap.peek(), None);
180 /// // Let's add some scores...
185 /// // Now peek shows the most important item in the heap.
186 /// assert_eq!(heap.peek(), Some(&5));
188 /// // We can check the length of a heap.
189 /// assert_eq!(heap.len(), 3);
191 /// // We can iterate over the items in the heap, although they are returned in
192 /// // a random order.
194 /// println!("{}", x);
197 /// // If we instead pop these scores, they should come back in order.
198 /// assert_eq!(heap.pop(), Some(5));
199 /// assert_eq!(heap.pop(), Some(2));
200 /// assert_eq!(heap.pop(), Some(1));
201 /// assert_eq!(heap.pop(), None);
203 /// // We can clear the heap of any remaining items.
206 /// // The heap should now be empty.
207 /// assert!(heap.is_empty())
212 /// Either `std::cmp::Reverse` or a custom `Ord` implementation can be used to
213 /// make `BinaryHeap` a min-heap. This makes `heap.pop()` return the smallest
214 /// value instead of the greatest one.
217 /// use std::collections::BinaryHeap;
218 /// use std::cmp::Reverse;
220 /// let mut heap = BinaryHeap::new();
222 /// // Wrap values in `Reverse`
223 /// heap.push(Reverse(1));
224 /// heap.push(Reverse(5));
225 /// heap.push(Reverse(2));
227 /// // If we pop these scores now, they should come back in the reverse order.
228 /// assert_eq!(heap.pop(), Some(Reverse(1)));
229 /// assert_eq!(heap.pop(), Some(Reverse(2)));
230 /// assert_eq!(heap.pop(), Some(Reverse(5)));
231 /// assert_eq!(heap.pop(), None);
234 /// # Time complexity
236 /// | [push] | [pop] | [peek]/[peek\_mut] |
237 /// |--------|-----------|--------------------|
238 /// | O(1)~ | *O*(log(*n*)) | *O*(1) |
240 /// The value for `push` is an expected cost; the method documentation gives a
241 /// more detailed analysis.
243 /// [push]: #method.push
244 /// [pop]: #method.pop
245 /// [peek]: #method.peek
246 /// [peek\_mut]: #method.peek_mut
247 #[stable(feature = "rust1", since = "1.0.0")]
248 pub struct BinaryHeap<T> {
252 /// Structure wrapping a mutable reference to the greatest item on a
255 /// This `struct` is created by the [`peek_mut`] method on [`BinaryHeap`]. See
256 /// its documentation for more.
258 /// [`peek_mut`]: struct.BinaryHeap.html#method.peek_mut
259 /// [`BinaryHeap`]: struct.BinaryHeap.html
260 #[stable(feature = "binary_heap_peek_mut", since = "1.12.0")]
261 pub struct PeekMut<'a, T: 'a + Ord> {
262 heap: &'a mut BinaryHeap<T>,
266 #[stable(feature = "collection_debug", since = "1.17.0")]
267 impl<T: Ord + fmt::Debug> fmt::Debug for PeekMut<'_, T> {
268 fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
269 f.debug_tuple("PeekMut").field(&self.heap.data[0]).finish()
273 #[stable(feature = "binary_heap_peek_mut", since = "1.12.0")]
274 impl<T: Ord> Drop for PeekMut<'_, T> {
277 self.heap.sift_down(0);
282 #[stable(feature = "binary_heap_peek_mut", since = "1.12.0")]
283 impl<T: Ord> Deref for PeekMut<'_, T> {
285 fn deref(&self) -> &T {
286 debug_assert!(!self.heap.is_empty());
287 // SAFE: PeekMut is only instantiated for non-empty heaps
288 unsafe { self.heap.data.get_unchecked(0) }
292 #[stable(feature = "binary_heap_peek_mut", since = "1.12.0")]
293 impl<T: Ord> DerefMut for PeekMut<'_, T> {
294 fn deref_mut(&mut self) -> &mut T {
295 debug_assert!(!self.heap.is_empty());
296 // SAFE: PeekMut is only instantiated for non-empty heaps
297 unsafe { self.heap.data.get_unchecked_mut(0) }
301 impl<'a, T: Ord> PeekMut<'a, T> {
302 /// Removes the peeked value from the heap and returns it.
303 #[stable(feature = "binary_heap_peek_mut_pop", since = "1.18.0")]
304 pub fn pop(mut this: PeekMut<'a, T>) -> T {
305 let value = this.heap.pop().unwrap();
311 #[stable(feature = "rust1", since = "1.0.0")]
312 impl<T: Clone> Clone for BinaryHeap<T> {
313 fn clone(&self) -> Self {
314 BinaryHeap { data: self.data.clone() }
317 fn clone_from(&mut self, source: &Self) {
318 self.data.clone_from(&source.data);
322 #[stable(feature = "rust1", since = "1.0.0")]
323 impl<T: Ord> Default for BinaryHeap<T> {
324 /// Creates an empty `BinaryHeap<T>`.
326 fn default() -> BinaryHeap<T> {
331 #[stable(feature = "binaryheap_debug", since = "1.4.0")]
332 impl<T: fmt::Debug> fmt::Debug for BinaryHeap<T> {
333 fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
334 f.debug_list().entries(self.iter()).finish()
338 impl<T: Ord> BinaryHeap<T> {
339 /// Creates an empty `BinaryHeap` as a max-heap.
346 /// use std::collections::BinaryHeap;
347 /// let mut heap = BinaryHeap::new();
350 #[stable(feature = "rust1", since = "1.0.0")]
351 pub fn new() -> BinaryHeap<T> {
352 BinaryHeap { data: vec![] }
355 /// Creates an empty `BinaryHeap` with a specific capacity.
356 /// This preallocates enough memory for `capacity` elements,
357 /// so that the `BinaryHeap` does not have to be reallocated
358 /// until it contains at least that many values.
365 /// use std::collections::BinaryHeap;
366 /// let mut heap = BinaryHeap::with_capacity(10);
369 #[stable(feature = "rust1", since = "1.0.0")]
370 pub fn with_capacity(capacity: usize) -> BinaryHeap<T> {
371 BinaryHeap { data: Vec::with_capacity(capacity) }
374 /// Returns a mutable reference to the greatest item in the binary heap, or
375 /// `None` if it is empty.
377 /// Note: If the `PeekMut` value is leaked, the heap may be in an
378 /// inconsistent state.
385 /// use std::collections::BinaryHeap;
386 /// let mut heap = BinaryHeap::new();
387 /// assert!(heap.peek_mut().is_none());
393 /// let mut val = heap.peek_mut().unwrap();
396 /// assert_eq!(heap.peek(), Some(&2));
399 /// # Time complexity
401 /// Cost is *O*(1) in the worst case.
402 #[stable(feature = "binary_heap_peek_mut", since = "1.12.0")]
403 pub fn peek_mut(&mut self) -> Option<PeekMut<'_, T>> {
404 if self.is_empty() { None } else { Some(PeekMut { heap: self, sift: true }) }
407 /// Removes the greatest item from the binary heap and returns it, or `None` if it
415 /// use std::collections::BinaryHeap;
416 /// let mut heap = BinaryHeap::from(vec![1, 3]);
418 /// assert_eq!(heap.pop(), Some(3));
419 /// assert_eq!(heap.pop(), Some(1));
420 /// assert_eq!(heap.pop(), None);
423 /// # Time complexity
425 /// The worst case cost of `pop` on a heap containing *n* elements is *O*(log(*n*)).
426 #[stable(feature = "rust1", since = "1.0.0")]
427 pub fn pop(&mut self) -> Option<T> {
428 self.data.pop().map(|mut item| {
429 if !self.is_empty() {
430 swap(&mut item, &mut self.data[0]);
431 self.sift_down_to_bottom(0);
437 /// Pushes an item onto the binary heap.
444 /// use std::collections::BinaryHeap;
445 /// let mut heap = BinaryHeap::new();
450 /// assert_eq!(heap.len(), 3);
451 /// assert_eq!(heap.peek(), Some(&5));
454 /// # Time complexity
456 /// The expected cost of `push`, averaged over every possible ordering of
457 /// the elements being pushed, and over a sufficiently large number of
458 /// pushes, is *O*(1). This is the most meaningful cost metric when pushing
459 /// elements that are *not* already in any sorted pattern.
461 /// The time complexity degrades if elements are pushed in predominantly
462 /// ascending order. In the worst case, elements are pushed in ascending
463 /// sorted order and the amortized cost per push is *O*(log(*n*)) against a heap
464 /// containing *n* elements.
466 /// The worst case cost of a *single* call to `push` is *O*(*n*). The worst case
467 /// occurs when capacity is exhausted and needs a resize. The resize cost
468 /// has been amortized in the previous figures.
469 #[stable(feature = "rust1", since = "1.0.0")]
470 pub fn push(&mut self, item: T) {
471 let old_len = self.len();
472 self.data.push(item);
473 self.sift_up(0, old_len);
476 /// Consumes the `BinaryHeap` and returns a vector in sorted
477 /// (ascending) order.
484 /// use std::collections::BinaryHeap;
486 /// let mut heap = BinaryHeap::from(vec![1, 2, 4, 5, 7]);
490 /// let vec = heap.into_sorted_vec();
491 /// assert_eq!(vec, [1, 2, 3, 4, 5, 6, 7]);
493 #[stable(feature = "binary_heap_extras_15", since = "1.5.0")]
494 pub fn into_sorted_vec(mut self) -> Vec<T> {
495 let mut end = self.len();
498 self.data.swap(0, end);
499 self.sift_down_range(0, end);
504 // The implementations of sift_up and sift_down use unsafe blocks in
505 // order to move an element out of the vector (leaving behind a
506 // hole), shift along the others and move the removed element back into the
507 // vector at the final location of the hole.
508 // The `Hole` type is used to represent this, and make sure
509 // the hole is filled back at the end of its scope, even on panic.
510 // Using a hole reduces the constant factor compared to using swaps,
511 // which involves twice as many moves.
512 fn sift_up(&mut self, start: usize, pos: usize) -> usize {
514 // Take out the value at `pos` and create a hole.
515 let mut hole = Hole::new(&mut self.data, pos);
517 while hole.pos() > start {
518 let parent = (hole.pos() - 1) / 2;
519 if hole.element() <= hole.get(parent) {
522 hole.move_to(parent);
528 /// Take an element at `pos` and move it down the heap,
529 /// while its children are larger.
530 fn sift_down_range(&mut self, pos: usize, end: usize) {
532 let mut hole = Hole::new(&mut self.data, pos);
533 let mut child = 2 * pos + 1;
535 let right = child + 1;
536 // compare with the greater of the two children
537 if right < end && hole.get(child) <= hole.get(right) {
540 // if we are already in order, stop.
541 if hole.element() >= hole.get(child) {
545 child = 2 * hole.pos() + 1;
550 fn sift_down(&mut self, pos: usize) {
551 let len = self.len();
552 self.sift_down_range(pos, len);
555 /// Take an element at `pos` and move it all the way down the heap,
556 /// then sift it up to its position.
558 /// Note: This is faster when the element is known to be large / should
559 /// be closer to the bottom.
560 fn sift_down_to_bottom(&mut self, mut pos: usize) {
561 let end = self.len();
564 let mut hole = Hole::new(&mut self.data, pos);
565 let mut child = 2 * pos + 1;
567 let right = child + 1;
568 // compare with the greater of the two children
569 if right < end && hole.get(child) <= hole.get(right) {
573 child = 2 * hole.pos() + 1;
577 self.sift_up(start, pos);
580 fn rebuild(&mut self) {
581 let mut n = self.len() / 2;
588 /// Moves all the elements of `other` into `self`, leaving `other` empty.
595 /// use std::collections::BinaryHeap;
597 /// let v = vec![-10, 1, 2, 3, 3];
598 /// let mut a = BinaryHeap::from(v);
600 /// let v = vec![-20, 5, 43];
601 /// let mut b = BinaryHeap::from(v);
603 /// a.append(&mut b);
605 /// assert_eq!(a.into_sorted_vec(), [-20, -10, 1, 2, 3, 3, 5, 43]);
606 /// assert!(b.is_empty());
608 #[stable(feature = "binary_heap_append", since = "1.11.0")]
609 pub fn append(&mut self, other: &mut Self) {
610 if self.len() < other.len() {
614 if other.is_empty() {
619 fn log2_fast(x: usize) -> usize {
620 8 * size_of::<usize>() - (x.leading_zeros() as usize) - 1
623 // `rebuild` takes O(len1 + len2) operations
624 // and about 2 * (len1 + len2) comparisons in the worst case
625 // while `extend` takes O(len2 * log(len1)) operations
626 // and about 1 * len2 * log_2(len1) comparisons in the worst case,
627 // assuming len1 >= len2.
629 fn better_to_rebuild(len1: usize, len2: usize) -> bool {
630 2 * (len1 + len2) < len2 * log2_fast(len1)
633 if better_to_rebuild(self.len(), other.len()) {
634 self.data.append(&mut other.data);
637 self.extend(other.drain());
641 /// Returns an iterator which retrieves elements in heap order.
642 /// The retrieved elements are removed from the original heap.
643 /// The remaining elements will be removed on drop in heap order.
646 /// * `.drain_sorted()` is *O*(*n* \* log(*n*)); much slower than `.drain()`.
647 /// You should use the latter for most cases.
654 /// #![feature(binary_heap_drain_sorted)]
655 /// use std::collections::BinaryHeap;
657 /// let mut heap = BinaryHeap::from(vec![1, 2, 3, 4, 5]);
658 /// assert_eq!(heap.len(), 5);
660 /// drop(heap.drain_sorted()); // removes all elements in heap order
661 /// assert_eq!(heap.len(), 0);
664 #[unstable(feature = "binary_heap_drain_sorted", issue = "59278")]
665 pub fn drain_sorted(&mut self) -> DrainSorted<'_, T> {
666 DrainSorted { inner: self }
669 /// Retains only the elements specified by the predicate.
671 /// In other words, remove all elements `e` such that `f(&e)` returns
672 /// `false`. The elements are visited in unsorted (and unspecified) order.
679 /// #![feature(binary_heap_retain)]
680 /// use std::collections::BinaryHeap;
682 /// let mut heap = BinaryHeap::from(vec![-10, -5, 1, 2, 4, 13]);
684 /// heap.retain(|x| x % 2 == 0); // only keep even numbers
686 /// assert_eq!(heap.into_sorted_vec(), [-10, 2, 4])
688 #[unstable(feature = "binary_heap_retain", issue = "71503")]
689 pub fn retain<F>(&mut self, f: F)
691 F: FnMut(&T) -> bool,
698 impl<T> BinaryHeap<T> {
699 /// Returns an iterator visiting all values in the underlying vector, in
707 /// use std::collections::BinaryHeap;
708 /// let heap = BinaryHeap::from(vec![1, 2, 3, 4]);
710 /// // Print 1, 2, 3, 4 in arbitrary order
711 /// for x in heap.iter() {
712 /// println!("{}", x);
715 #[stable(feature = "rust1", since = "1.0.0")]
716 pub fn iter(&self) -> Iter<'_, T> {
717 Iter { iter: self.data.iter() }
720 /// Returns an iterator which retrieves elements in heap order.
721 /// This method consumes the original heap.
728 /// #![feature(binary_heap_into_iter_sorted)]
729 /// use std::collections::BinaryHeap;
730 /// let heap = BinaryHeap::from(vec![1, 2, 3, 4, 5]);
732 /// assert_eq!(heap.into_iter_sorted().take(2).collect::<Vec<_>>(), vec![5, 4]);
734 #[unstable(feature = "binary_heap_into_iter_sorted", issue = "59278")]
735 pub fn into_iter_sorted(self) -> IntoIterSorted<T> {
736 IntoIterSorted { inner: self }
739 /// Returns the greatest item in the binary heap, or `None` if it is empty.
746 /// use std::collections::BinaryHeap;
747 /// let mut heap = BinaryHeap::new();
748 /// assert_eq!(heap.peek(), None);
753 /// assert_eq!(heap.peek(), Some(&5));
757 /// # Time complexity
759 /// Cost is *O*(1) in the worst case.
760 #[stable(feature = "rust1", since = "1.0.0")]
761 pub fn peek(&self) -> Option<&T> {
765 /// Returns the number of elements the binary heap can hold without reallocating.
772 /// use std::collections::BinaryHeap;
773 /// let mut heap = BinaryHeap::with_capacity(100);
774 /// assert!(heap.capacity() >= 100);
777 #[stable(feature = "rust1", since = "1.0.0")]
778 pub fn capacity(&self) -> usize {
782 /// Reserves the minimum capacity for exactly `additional` more elements to be inserted in the
783 /// given `BinaryHeap`. Does nothing if the capacity is already sufficient.
785 /// Note that the allocator may give the collection more space than it requests. Therefore
786 /// capacity can not be relied upon to be precisely minimal. Prefer [`reserve`] if future
787 /// insertions are expected.
791 /// Panics if the new capacity overflows `usize`.
798 /// use std::collections::BinaryHeap;
799 /// let mut heap = BinaryHeap::new();
800 /// heap.reserve_exact(100);
801 /// assert!(heap.capacity() >= 100);
805 /// [`reserve`]: #method.reserve
806 #[stable(feature = "rust1", since = "1.0.0")]
807 pub fn reserve_exact(&mut self, additional: usize) {
808 self.data.reserve_exact(additional);
811 /// Reserves capacity for at least `additional` more elements to be inserted in the
812 /// `BinaryHeap`. The collection may reserve more space to avoid frequent reallocations.
816 /// Panics if the new capacity overflows `usize`.
823 /// use std::collections::BinaryHeap;
824 /// let mut heap = BinaryHeap::new();
825 /// heap.reserve(100);
826 /// assert!(heap.capacity() >= 100);
829 #[stable(feature = "rust1", since = "1.0.0")]
830 pub fn reserve(&mut self, additional: usize) {
831 self.data.reserve(additional);
834 /// Discards as much additional capacity as possible.
841 /// use std::collections::BinaryHeap;
842 /// let mut heap: BinaryHeap<i32> = BinaryHeap::with_capacity(100);
844 /// assert!(heap.capacity() >= 100);
845 /// heap.shrink_to_fit();
846 /// assert!(heap.capacity() == 0);
848 #[stable(feature = "rust1", since = "1.0.0")]
849 pub fn shrink_to_fit(&mut self) {
850 self.data.shrink_to_fit();
853 /// Discards capacity with a lower bound.
855 /// The capacity will remain at least as large as both the length
856 /// and the supplied value.
858 /// Panics if the current capacity is smaller than the supplied
859 /// minimum capacity.
864 /// #![feature(shrink_to)]
865 /// use std::collections::BinaryHeap;
866 /// let mut heap: BinaryHeap<i32> = BinaryHeap::with_capacity(100);
868 /// assert!(heap.capacity() >= 100);
869 /// heap.shrink_to(10);
870 /// assert!(heap.capacity() >= 10);
873 #[unstable(feature = "shrink_to", reason = "new API", issue = "56431")]
874 pub fn shrink_to(&mut self, min_capacity: usize) {
875 self.data.shrink_to(min_capacity)
878 /// Consumes the `BinaryHeap` and returns the underlying vector
879 /// in arbitrary order.
886 /// use std::collections::BinaryHeap;
887 /// let heap = BinaryHeap::from(vec![1, 2, 3, 4, 5, 6, 7]);
888 /// let vec = heap.into_vec();
890 /// // Will print in some order
892 /// println!("{}", x);
895 #[stable(feature = "binary_heap_extras_15", since = "1.5.0")]
896 pub fn into_vec(self) -> Vec<T> {
900 /// Returns the length of the binary heap.
907 /// use std::collections::BinaryHeap;
908 /// let heap = BinaryHeap::from(vec![1, 3]);
910 /// assert_eq!(heap.len(), 2);
912 #[stable(feature = "rust1", since = "1.0.0")]
913 pub fn len(&self) -> usize {
917 /// Checks if the binary heap is empty.
924 /// use std::collections::BinaryHeap;
925 /// let mut heap = BinaryHeap::new();
927 /// assert!(heap.is_empty());
933 /// assert!(!heap.is_empty());
935 #[stable(feature = "rust1", since = "1.0.0")]
936 pub fn is_empty(&self) -> bool {
940 /// Clears the binary heap, returning an iterator over the removed elements.
942 /// The elements are removed in arbitrary order.
949 /// use std::collections::BinaryHeap;
950 /// let mut heap = BinaryHeap::from(vec![1, 3]);
952 /// assert!(!heap.is_empty());
954 /// for x in heap.drain() {
955 /// println!("{}", x);
958 /// assert!(heap.is_empty());
961 #[stable(feature = "drain", since = "1.6.0")]
962 pub fn drain(&mut self) -> Drain<'_, T> {
963 Drain { iter: self.data.drain(..) }
966 /// Drops all items from the binary heap.
973 /// use std::collections::BinaryHeap;
974 /// let mut heap = BinaryHeap::from(vec![1, 3]);
976 /// assert!(!heap.is_empty());
980 /// assert!(heap.is_empty());
982 #[stable(feature = "rust1", since = "1.0.0")]
983 pub fn clear(&mut self) {
988 /// Hole represents a hole in a slice i.e., an index without valid value
989 /// (because it was moved from or duplicated).
990 /// In drop, `Hole` will restore the slice by filling the hole
991 /// position with the value that was originally removed.
992 struct Hole<'a, T: 'a> {
994 elt: ManuallyDrop<T>,
998 impl<'a, T> Hole<'a, T> {
999 /// Create a new `Hole` at index `pos`.
1001 /// Unsafe because pos must be within the data slice.
1003 unsafe fn new(data: &'a mut [T], pos: usize) -> Self {
1004 debug_assert!(pos < data.len());
1005 // SAFE: pos should be inside the slice
1006 let elt = unsafe { ptr::read(data.get_unchecked(pos)) };
1007 Hole { data, elt: ManuallyDrop::new(elt), pos }
1011 fn pos(&self) -> usize {
1015 /// Returns a reference to the element removed.
1017 fn element(&self) -> &T {
1021 /// Returns a reference to the element at `index`.
1023 /// Unsafe because index must be within the data slice and not equal to pos.
1025 unsafe fn get(&self, index: usize) -> &T {
1026 debug_assert!(index != self.pos);
1027 debug_assert!(index < self.data.len());
1028 unsafe { self.data.get_unchecked(index) }
1031 /// Move hole to new location
1033 /// Unsafe because index must be within the data slice and not equal to pos.
1035 unsafe fn move_to(&mut self, index: usize) {
1036 debug_assert!(index != self.pos);
1037 debug_assert!(index < self.data.len());
1039 let index_ptr: *const _ = self.data.get_unchecked(index);
1040 let hole_ptr = self.data.get_unchecked_mut(self.pos);
1041 ptr::copy_nonoverlapping(index_ptr, hole_ptr, 1);
1047 impl<T> Drop for Hole<'_, T> {
1049 fn drop(&mut self) {
1050 // fill the hole again
1053 ptr::copy_nonoverlapping(&*self.elt, self.data.get_unchecked_mut(pos), 1);
1058 /// An iterator over the elements of a `BinaryHeap`.
1060 /// This `struct` is created by the [`iter`] method on [`BinaryHeap`]. See its
1061 /// documentation for more.
1063 /// [`iter`]: struct.BinaryHeap.html#method.iter
1064 /// [`BinaryHeap`]: struct.BinaryHeap.html
1065 #[stable(feature = "rust1", since = "1.0.0")]
1066 pub struct Iter<'a, T: 'a> {
1067 iter: slice::Iter<'a, T>,
1070 #[stable(feature = "collection_debug", since = "1.17.0")]
1071 impl<T: fmt::Debug> fmt::Debug for Iter<'_, T> {
1072 fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
1073 f.debug_tuple("Iter").field(&self.iter.as_slice()).finish()
1077 // FIXME(#26925) Remove in favor of `#[derive(Clone)]`
1078 #[stable(feature = "rust1", since = "1.0.0")]
1079 impl<T> Clone for Iter<'_, T> {
1080 fn clone(&self) -> Self {
1081 Iter { iter: self.iter.clone() }
1085 #[stable(feature = "rust1", since = "1.0.0")]
1086 impl<'a, T> Iterator for Iter<'a, T> {
1090 fn next(&mut self) -> Option<&'a T> {
1095 fn size_hint(&self) -> (usize, Option<usize>) {
1096 self.iter.size_hint()
1100 fn last(self) -> Option<&'a T> {
1105 #[stable(feature = "rust1", since = "1.0.0")]
1106 impl<'a, T> DoubleEndedIterator for Iter<'a, T> {
1108 fn next_back(&mut self) -> Option<&'a T> {
1109 self.iter.next_back()
1113 #[stable(feature = "rust1", since = "1.0.0")]
1114 impl<T> ExactSizeIterator for Iter<'_, T> {
1115 fn is_empty(&self) -> bool {
1116 self.iter.is_empty()
1120 #[stable(feature = "fused", since = "1.26.0")]
1121 impl<T> FusedIterator for Iter<'_, T> {}
1123 /// An owning iterator over the elements of a `BinaryHeap`.
1125 /// This `struct` is created by the [`into_iter`] method on [`BinaryHeap`]
1126 /// (provided by the `IntoIterator` trait). See its documentation for more.
1128 /// [`into_iter`]: struct.BinaryHeap.html#method.into_iter
1129 /// [`BinaryHeap`]: struct.BinaryHeap.html
1130 #[stable(feature = "rust1", since = "1.0.0")]
1132 pub struct IntoIter<T> {
1133 iter: vec::IntoIter<T>,
1136 #[stable(feature = "collection_debug", since = "1.17.0")]
1137 impl<T: fmt::Debug> fmt::Debug for IntoIter<T> {
1138 fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
1139 f.debug_tuple("IntoIter").field(&self.iter.as_slice()).finish()
1143 #[stable(feature = "rust1", since = "1.0.0")]
1144 impl<T> Iterator for IntoIter<T> {
1148 fn next(&mut self) -> Option<T> {
1153 fn size_hint(&self) -> (usize, Option<usize>) {
1154 self.iter.size_hint()
1158 #[stable(feature = "rust1", since = "1.0.0")]
1159 impl<T> DoubleEndedIterator for IntoIter<T> {
1161 fn next_back(&mut self) -> Option<T> {
1162 self.iter.next_back()
1166 #[stable(feature = "rust1", since = "1.0.0")]
1167 impl<T> ExactSizeIterator for IntoIter<T> {
1168 fn is_empty(&self) -> bool {
1169 self.iter.is_empty()
1173 #[stable(feature = "fused", since = "1.26.0")]
1174 impl<T> FusedIterator for IntoIter<T> {}
1176 #[unstable(issue = "none", feature = "inplace_iteration")]
1177 unsafe impl<T> SourceIter for IntoIter<T> {
1178 type Source = IntoIter<T>;
1181 unsafe fn as_inner(&mut self) -> &mut Self::Source {
1186 #[unstable(issue = "none", feature = "inplace_iteration")]
1187 unsafe impl<I> InPlaceIterable for IntoIter<I> {}
1189 impl<I> AsIntoIter for IntoIter<I> {
1192 fn as_into_iter(&mut self) -> &mut vec::IntoIter<Self::Item> {
1197 #[unstable(feature = "binary_heap_into_iter_sorted", issue = "59278")]
1198 #[derive(Clone, Debug)]
1199 pub struct IntoIterSorted<T> {
1200 inner: BinaryHeap<T>,
1203 #[unstable(feature = "binary_heap_into_iter_sorted", issue = "59278")]
1204 impl<T: Ord> Iterator for IntoIterSorted<T> {
1208 fn next(&mut self) -> Option<T> {
1213 fn size_hint(&self) -> (usize, Option<usize>) {
1214 let exact = self.inner.len();
1215 (exact, Some(exact))
1219 #[unstable(feature = "binary_heap_into_iter_sorted", issue = "59278")]
1220 impl<T: Ord> ExactSizeIterator for IntoIterSorted<T> {}
1222 #[unstable(feature = "binary_heap_into_iter_sorted", issue = "59278")]
1223 impl<T: Ord> FusedIterator for IntoIterSorted<T> {}
1225 #[unstable(feature = "trusted_len", issue = "37572")]
1226 unsafe impl<T: Ord> TrustedLen for IntoIterSorted<T> {}
1228 /// A draining iterator over the elements of a `BinaryHeap`.
1230 /// This `struct` is created by the [`drain`] method on [`BinaryHeap`]. See its
1231 /// documentation for more.
1233 /// [`drain`]: struct.BinaryHeap.html#method.drain
1234 /// [`BinaryHeap`]: struct.BinaryHeap.html
1235 #[stable(feature = "drain", since = "1.6.0")]
1237 pub struct Drain<'a, T: 'a> {
1238 iter: vec::Drain<'a, T>,
1241 #[stable(feature = "drain", since = "1.6.0")]
1242 impl<T> Iterator for Drain<'_, T> {
1246 fn next(&mut self) -> Option<T> {
1251 fn size_hint(&self) -> (usize, Option<usize>) {
1252 self.iter.size_hint()
1256 #[stable(feature = "drain", since = "1.6.0")]
1257 impl<T> DoubleEndedIterator for Drain<'_, T> {
1259 fn next_back(&mut self) -> Option<T> {
1260 self.iter.next_back()
1264 #[stable(feature = "drain", since = "1.6.0")]
1265 impl<T> ExactSizeIterator for Drain<'_, T> {
1266 fn is_empty(&self) -> bool {
1267 self.iter.is_empty()
1271 #[stable(feature = "fused", since = "1.26.0")]
1272 impl<T> FusedIterator for Drain<'_, T> {}
1274 /// A draining iterator over the elements of a `BinaryHeap`.
1276 /// This `struct` is created by the [`drain_sorted`] method on [`BinaryHeap`]. See its
1277 /// documentation for more.
1279 /// [`drain_sorted`]: struct.BinaryHeap.html#method.drain_sorted
1280 /// [`BinaryHeap`]: struct.BinaryHeap.html
1281 #[unstable(feature = "binary_heap_drain_sorted", issue = "59278")]
1283 pub struct DrainSorted<'a, T: Ord> {
1284 inner: &'a mut BinaryHeap<T>,
1287 #[unstable(feature = "binary_heap_drain_sorted", issue = "59278")]
1288 impl<'a, T: Ord> Drop for DrainSorted<'a, T> {
1289 /// Removes heap elements in heap order.
1290 fn drop(&mut self) {
1291 struct DropGuard<'r, 'a, T: Ord>(&'r mut DrainSorted<'a, T>);
1293 impl<'r, 'a, T: Ord> Drop for DropGuard<'r, 'a, T> {
1294 fn drop(&mut self) {
1295 while self.0.inner.pop().is_some() {}
1299 while let Some(item) = self.inner.pop() {
1300 let guard = DropGuard(self);
1307 #[unstable(feature = "binary_heap_drain_sorted", issue = "59278")]
1308 impl<T: Ord> Iterator for DrainSorted<'_, 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_drain_sorted", issue = "59278")]
1324 impl<T: Ord> ExactSizeIterator for DrainSorted<'_, T> {}
1326 #[unstable(feature = "binary_heap_drain_sorted", issue = "59278")]
1327 impl<T: Ord> FusedIterator for DrainSorted<'_, T> {}
1329 #[unstable(feature = "trusted_len", issue = "37572")]
1330 unsafe impl<T: Ord> TrustedLen for DrainSorted<'_, T> {}
1332 #[stable(feature = "binary_heap_extras_15", since = "1.5.0")]
1333 impl<T: Ord> From<Vec<T>> for BinaryHeap<T> {
1334 /// Converts a `Vec<T>` into a `BinaryHeap<T>`.
1336 /// This conversion happens in-place, and has *O*(*n*) time complexity.
1337 fn from(vec: Vec<T>) -> BinaryHeap<T> {
1338 let mut heap = BinaryHeap { data: vec };
1344 #[stable(feature = "binary_heap_extras_15", since = "1.5.0")]
1345 impl<T> From<BinaryHeap<T>> for Vec<T> {
1346 /// Converts a `BinaryHeap<T>` into a `Vec<T>`.
1348 /// This conversion requires no data movement or allocation, and has
1349 /// constant time complexity.
1350 fn from(heap: BinaryHeap<T>) -> Vec<T> {
1355 #[stable(feature = "rust1", since = "1.0.0")]
1356 impl<T: Ord> FromIterator<T> for BinaryHeap<T> {
1357 fn from_iter<I: IntoIterator<Item = T>>(iter: I) -> BinaryHeap<T> {
1358 BinaryHeap::from(iter.into_iter().collect::<Vec<_>>())
1362 #[stable(feature = "rust1", since = "1.0.0")]
1363 impl<T> IntoIterator for BinaryHeap<T> {
1365 type IntoIter = IntoIter<T>;
1367 /// Creates a consuming iterator, that is, one that moves each value out of
1368 /// the binary heap in arbitrary order. The binary heap cannot be used
1369 /// after calling this.
1376 /// use std::collections::BinaryHeap;
1377 /// let heap = BinaryHeap::from(vec![1, 2, 3, 4]);
1379 /// // Print 1, 2, 3, 4 in arbitrary order
1380 /// for x in heap.into_iter() {
1381 /// // x has type i32, not &i32
1382 /// println!("{}", x);
1385 fn into_iter(self) -> IntoIter<T> {
1386 IntoIter { iter: self.data.into_iter() }
1390 #[stable(feature = "rust1", since = "1.0.0")]
1391 impl<'a, T> IntoIterator for &'a BinaryHeap<T> {
1393 type IntoIter = Iter<'a, T>;
1395 fn into_iter(self) -> Iter<'a, T> {
1400 #[stable(feature = "rust1", since = "1.0.0")]
1401 impl<T: Ord> Extend<T> for BinaryHeap<T> {
1403 fn extend<I: IntoIterator<Item = T>>(&mut self, iter: I) {
1404 <Self as SpecExtend<I>>::spec_extend(self, iter);
1408 fn extend_one(&mut self, item: T) {
1413 fn extend_reserve(&mut self, additional: usize) {
1414 self.reserve(additional);
1418 impl<T: Ord, I: IntoIterator<Item = T>> SpecExtend<I> for BinaryHeap<T> {
1419 default fn spec_extend(&mut self, iter: I) {
1420 self.extend_desugared(iter.into_iter());
1424 impl<T: Ord> SpecExtend<BinaryHeap<T>> for BinaryHeap<T> {
1425 fn spec_extend(&mut self, ref mut other: BinaryHeap<T>) {
1430 impl<T: Ord> BinaryHeap<T> {
1431 fn extend_desugared<I: IntoIterator<Item = T>>(&mut self, iter: I) {
1432 let iterator = iter.into_iter();
1433 let (lower, _) = iterator.size_hint();
1435 self.reserve(lower);
1437 iterator.for_each(move |elem| self.push(elem));
1441 #[stable(feature = "extend_ref", since = "1.2.0")]
1442 impl<'a, T: 'a + Ord + Copy> Extend<&'a T> for BinaryHeap<T> {
1443 fn extend<I: IntoIterator<Item = &'a T>>(&mut self, iter: I) {
1444 self.extend(iter.into_iter().cloned());
1448 fn extend_one(&mut self, &item: &'a T) {
1453 fn extend_reserve(&mut self, additional: usize) {
1454 self.reserve(additional);