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
7 //! log n)` in-place heapsort.
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]: http://en.wikipedia.org/wiki/Dijkstra%27s_algorithm
16 //! [sssp]: http://en.wikipedia.org/wiki/Shortest_path_problem
17 //! [dir_graph]: http://en.wikipedia.org/wiki/Directed_graph
18 //! [`BinaryHeap`]: struct.BinaryHeap.html
21 //! use std::cmp::Ordering;
22 //! use std::collections::BinaryHeap;
25 //! #[derive(Copy, Clone, Eq, PartialEq)]
31 //! // The priority queue depends on `Ord`.
32 //! // Explicitly implement the trait so the queue becomes a min-heap
33 //! // instead of a max-heap.
34 //! impl Ord for State {
35 //! fn cmp(&self, other: &State) -> Ordering {
36 //! // Notice that the we flip the ordering on costs.
37 //! // In case of a tie we compare positions - this step is necessary
38 //! // to make implementations of `PartialEq` and `Ord` consistent.
39 //! other.cost.cmp(&self.cost)
40 //! .then_with(|| self.position.cmp(&other.position))
44 //! // `PartialOrd` needs to be implemented as well.
45 //! impl PartialOrd for State {
46 //! fn partial_cmp(&self, other: &State) -> Option<Ordering> {
47 //! Some(self.cmp(other))
51 //! // Each node is represented as an `usize`, for a shorter implementation.
57 //! // Dijkstra's shortest path algorithm.
59 //! // Start at `start` and use `dist` to track the current shortest distance
60 //! // to each node. This implementation isn't memory-efficient as it may leave duplicate
61 //! // nodes in the queue. It also uses `usize::MAX` as a sentinel value,
62 //! // for a simpler implementation.
63 //! fn shortest_path(adj_list: &Vec<Vec<Edge>>, start: usize, goal: usize) -> Option<usize> {
64 //! // dist[node] = current shortest distance from `start` to `node`
65 //! let mut dist: Vec<_> = (0..adj_list.len()).map(|_| usize::MAX).collect();
67 //! let mut heap = BinaryHeap::new();
69 //! // We're at `start`, with a zero cost
71 //! heap.push(State { cost: 0, position: start });
73 //! // Examine the frontier with lower cost nodes first (min-heap)
74 //! while let Some(State { cost, position }) = heap.pop() {
75 //! // Alternatively we could have continued to find all shortest paths
76 //! if position == goal { return Some(cost); }
78 //! // Important as we may have already found a better way
79 //! if cost > dist[position] { continue; }
81 //! // For each node we can reach, see if we can find a way with
82 //! // a lower cost going through this node
83 //! for edge in &adj_list[position] {
84 //! let next = State { cost: cost + edge.cost, position: edge.node };
86 //! // If so, add it to the frontier and continue
87 //! if next.cost < dist[next.position] {
89 //! // Relaxation, we have now found a better way
90 //! dist[next.position] = next.cost;
95 //! // Goal not reachable
100 //! // This is the directed graph we're going to use.
101 //! // The node numbers correspond to the different states,
102 //! // and the edge weights symbolize the cost of moving
103 //! // from one node to another.
104 //! // Note that the edges are one-way.
107 //! // +-----------------+
110 //! // 0 -----> 1 -----> 3 ---> 4
114 //! // +------> 2 -------+ |
116 //! // +---------------+
118 //! // The graph is represented as an adjacency list where each index,
119 //! // corresponding to a node value, has a list of outgoing edges.
120 //! // Chosen for its efficiency.
121 //! let graph = vec![
123 //! vec![Edge { node: 2, cost: 10 },
124 //! Edge { node: 1, cost: 1 }],
126 //! vec![Edge { node: 3, cost: 2 }],
128 //! vec![Edge { node: 1, cost: 1 },
129 //! Edge { node: 3, cost: 3 },
130 //! Edge { node: 4, cost: 1 }],
132 //! vec![Edge { node: 0, cost: 7 },
133 //! Edge { node: 4, cost: 2 }],
137 //! assert_eq!(shortest_path(&graph, 0, 1), Some(1));
138 //! assert_eq!(shortest_path(&graph, 0, 3), Some(3));
139 //! assert_eq!(shortest_path(&graph, 3, 0), Some(7));
140 //! assert_eq!(shortest_path(&graph, 0, 4), Some(5));
141 //! assert_eq!(shortest_path(&graph, 4, 0), None);
145 #![allow(missing_docs)]
146 #![stable(feature = "rust1", since = "1.0.0")]
148 use core::ops::{Deref, DerefMut};
149 use core::iter::{FromIterator, FusedIterator};
150 use core::mem::{swap, size_of, ManuallyDrop};
155 use crate::vec::{self, Vec};
157 use super::SpecExtend;
159 /// A priority queue implemented with a binary heap.
161 /// This will be a max-heap.
163 /// It is a logic error for an item to be modified in such a way that the
164 /// item's ordering relative to any other item, as determined by the `Ord`
165 /// trait, changes while it is in the heap. This is normally only possible
166 /// through `Cell`, `RefCell`, global state, I/O, or unsafe code.
171 /// use std::collections::BinaryHeap;
173 /// // Type inference lets us omit an explicit type signature (which
174 /// // would be `BinaryHeap<i32>` in this example).
175 /// let mut heap = BinaryHeap::new();
177 /// // We can use peek to look at the next item in the heap. In this case,
178 /// // there's no items in there yet so we get None.
179 /// assert_eq!(heap.peek(), None);
181 /// // Let's add some scores...
186 /// // Now peek shows the most important item in the heap.
187 /// assert_eq!(heap.peek(), Some(&5));
189 /// // We can check the length of a heap.
190 /// assert_eq!(heap.len(), 3);
192 /// // We can iterate over the items in the heap, although they are returned in
193 /// // a random order.
195 /// println!("{}", x);
198 /// // If we instead pop these scores, they should come back in order.
199 /// assert_eq!(heap.pop(), Some(5));
200 /// assert_eq!(heap.pop(), Some(2));
201 /// assert_eq!(heap.pop(), Some(1));
202 /// assert_eq!(heap.pop(), None);
204 /// // We can clear the heap of any remaining items.
207 /// // The heap should now be empty.
208 /// assert!(heap.is_empty())
213 /// Either `std::cmp::Reverse` or a custom `Ord` implementation can be used to
214 /// make `BinaryHeap` a min-heap. This makes `heap.pop()` return the smallest
215 /// value instead of the greatest one.
218 /// use std::collections::BinaryHeap;
219 /// use std::cmp::Reverse;
221 /// let mut heap = BinaryHeap::new();
223 /// // Wrap values in `Reverse`
224 /// heap.push(Reverse(1));
225 /// heap.push(Reverse(5));
226 /// heap.push(Reverse(2));
228 /// // If we pop these scores now, they should come back in the reverse order.
229 /// assert_eq!(heap.pop(), Some(Reverse(1)));
230 /// assert_eq!(heap.pop(), Some(Reverse(2)));
231 /// assert_eq!(heap.pop(), Some(Reverse(5)));
232 /// assert_eq!(heap.pop(), None);
234 #[stable(feature = "rust1", since = "1.0.0")]
235 pub struct BinaryHeap<T> {
239 /// Structure wrapping a mutable reference to the greatest item on a
242 /// This `struct` is created by the [`peek_mut`] method on [`BinaryHeap`]. See
243 /// its documentation for more.
245 /// [`peek_mut`]: struct.BinaryHeap.html#method.peek_mut
246 /// [`BinaryHeap`]: struct.BinaryHeap.html
247 #[stable(feature = "binary_heap_peek_mut", since = "1.12.0")]
248 pub struct PeekMut<'a, T: 'a + Ord> {
249 heap: &'a mut BinaryHeap<T>,
253 #[stable(feature = "collection_debug", since = "1.17.0")]
254 impl<T: Ord + fmt::Debug> fmt::Debug for PeekMut<'_, T> {
255 fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
256 f.debug_tuple("PeekMut")
257 .field(&self.heap.data[0])
262 #[stable(feature = "binary_heap_peek_mut", since = "1.12.0")]
263 impl<T: Ord> Drop for PeekMut<'_, T> {
266 self.heap.sift_down(0);
271 #[stable(feature = "binary_heap_peek_mut", since = "1.12.0")]
272 impl<T: Ord> Deref for PeekMut<'_, T> {
274 fn deref(&self) -> &T {
275 debug_assert!(!self.heap.is_empty());
276 // SAFE: PeekMut is only instantiated for non-empty heaps
277 unsafe { self.heap.data.get_unchecked(0) }
281 #[stable(feature = "binary_heap_peek_mut", since = "1.12.0")]
282 impl<T: Ord> DerefMut for PeekMut<'_, T> {
283 fn deref_mut(&mut self) -> &mut T {
284 debug_assert!(!self.heap.is_empty());
285 // SAFE: PeekMut is only instantiated for non-empty heaps
286 unsafe { self.heap.data.get_unchecked_mut(0) }
290 impl<'a, T: Ord> PeekMut<'a, T> {
291 /// Removes the peeked value from the heap and returns it.
292 #[stable(feature = "binary_heap_peek_mut_pop", since = "1.18.0")]
293 pub fn pop(mut this: PeekMut<'a, T>) -> T {
294 let value = this.heap.pop().unwrap();
300 #[stable(feature = "rust1", since = "1.0.0")]
301 impl<T: Clone> Clone for BinaryHeap<T> {
302 fn clone(&self) -> Self {
303 BinaryHeap { data: self.data.clone() }
306 fn clone_from(&mut self, source: &Self) {
307 self.data.clone_from(&source.data);
311 #[stable(feature = "rust1", since = "1.0.0")]
312 impl<T: Ord> Default for BinaryHeap<T> {
313 /// Creates an empty `BinaryHeap<T>`.
315 fn default() -> BinaryHeap<T> {
320 #[stable(feature = "binaryheap_debug", since = "1.4.0")]
321 impl<T: fmt::Debug> fmt::Debug for BinaryHeap<T> {
322 fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
323 f.debug_list().entries(self.iter()).finish()
327 impl<T: Ord> BinaryHeap<T> {
328 /// Creates an empty `BinaryHeap` as a max-heap.
335 /// use std::collections::BinaryHeap;
336 /// let mut heap = BinaryHeap::new();
339 #[stable(feature = "rust1", since = "1.0.0")]
340 pub fn new() -> BinaryHeap<T> {
341 BinaryHeap { data: vec![] }
344 /// Creates an empty `BinaryHeap` with a specific capacity.
345 /// This preallocates enough memory for `capacity` elements,
346 /// so that the `BinaryHeap` does not have to be reallocated
347 /// until it contains at least that many values.
354 /// use std::collections::BinaryHeap;
355 /// let mut heap = BinaryHeap::with_capacity(10);
358 #[stable(feature = "rust1", since = "1.0.0")]
359 pub fn with_capacity(capacity: usize) -> BinaryHeap<T> {
360 BinaryHeap { data: Vec::with_capacity(capacity) }
363 /// Returns a mutable reference to the greatest item in the binary heap, or
364 /// `None` if it is empty.
366 /// Note: If the `PeekMut` value is leaked, the heap may be in an
367 /// inconsistent state.
374 /// use std::collections::BinaryHeap;
375 /// let mut heap = BinaryHeap::new();
376 /// assert!(heap.peek_mut().is_none());
382 /// let mut val = heap.peek_mut().unwrap();
385 /// assert_eq!(heap.peek(), Some(&2));
387 #[stable(feature = "binary_heap_peek_mut", since = "1.12.0")]
388 pub fn peek_mut(&mut self) -> Option<PeekMut<'_, T>> {
399 /// Removes the greatest item from the binary heap and returns it, or `None` if it
407 /// use std::collections::BinaryHeap;
408 /// let mut heap = BinaryHeap::from(vec![1, 3]);
410 /// assert_eq!(heap.pop(), Some(3));
411 /// assert_eq!(heap.pop(), Some(1));
412 /// assert_eq!(heap.pop(), None);
414 #[stable(feature = "rust1", since = "1.0.0")]
415 pub fn pop(&mut self) -> Option<T> {
416 self.data.pop().map(|mut item| {
417 if !self.is_empty() {
418 swap(&mut item, &mut self.data[0]);
419 self.sift_down_to_bottom(0);
425 /// Pushes an item onto the binary heap.
432 /// use std::collections::BinaryHeap;
433 /// let mut heap = BinaryHeap::new();
438 /// assert_eq!(heap.len(), 3);
439 /// assert_eq!(heap.peek(), Some(&5));
441 #[stable(feature = "rust1", since = "1.0.0")]
442 pub fn push(&mut self, item: T) {
443 let old_len = self.len();
444 self.data.push(item);
445 self.sift_up(0, old_len);
448 /// Consumes the `BinaryHeap` and returns a vector in sorted
449 /// (ascending) order.
456 /// use std::collections::BinaryHeap;
458 /// let mut heap = BinaryHeap::from(vec![1, 2, 4, 5, 7]);
462 /// let vec = heap.into_sorted_vec();
463 /// assert_eq!(vec, [1, 2, 3, 4, 5, 6, 7]);
465 #[stable(feature = "binary_heap_extras_15", since = "1.5.0")]
466 pub fn into_sorted_vec(mut self) -> Vec<T> {
467 let mut end = self.len();
470 self.data.swap(0, end);
471 self.sift_down_range(0, end);
476 // The implementations of sift_up and sift_down use unsafe blocks in
477 // order to move an element out of the vector (leaving behind a
478 // hole), shift along the others and move the removed element back into the
479 // vector at the final location of the hole.
480 // The `Hole` type is used to represent this, and make sure
481 // the hole is filled back at the end of its scope, even on panic.
482 // Using a hole reduces the constant factor compared to using swaps,
483 // which involves twice as many moves.
484 fn sift_up(&mut self, start: usize, pos: usize) -> usize {
486 // Take out the value at `pos` and create a hole.
487 let mut hole = Hole::new(&mut self.data, pos);
489 while hole.pos() > start {
490 let parent = (hole.pos() - 1) / 2;
491 if hole.element() <= hole.get(parent) {
494 hole.move_to(parent);
500 /// Take an element at `pos` and move it down the heap,
501 /// while its children are larger.
502 fn sift_down_range(&mut self, pos: usize, end: usize) {
504 let mut hole = Hole::new(&mut self.data, pos);
505 let mut child = 2 * pos + 1;
507 let right = child + 1;
508 // compare with the greater of the two children
509 if right < end && !(hole.get(child) > hole.get(right)) {
512 // if we are already in order, stop.
513 if hole.element() >= hole.get(child) {
517 child = 2 * hole.pos() + 1;
522 fn sift_down(&mut self, pos: usize) {
523 let len = self.len();
524 self.sift_down_range(pos, len);
527 /// Take an element at `pos` and move it all the way down the heap,
528 /// then sift it up to its position.
530 /// Note: This is faster when the element is known to be large / should
531 /// be closer to the bottom.
532 fn sift_down_to_bottom(&mut self, mut pos: usize) {
533 let end = self.len();
536 let mut hole = Hole::new(&mut self.data, pos);
537 let mut child = 2 * pos + 1;
539 let right = child + 1;
540 // compare with the greater of the two children
541 if right < end && !(hole.get(child) > hole.get(right)) {
545 child = 2 * hole.pos() + 1;
549 self.sift_up(start, pos);
552 fn rebuild(&mut self) {
553 let mut n = self.len() / 2;
560 /// Moves all the elements of `other` into `self`, leaving `other` empty.
567 /// use std::collections::BinaryHeap;
569 /// let v = vec![-10, 1, 2, 3, 3];
570 /// let mut a = BinaryHeap::from(v);
572 /// let v = vec![-20, 5, 43];
573 /// let mut b = BinaryHeap::from(v);
575 /// a.append(&mut b);
577 /// assert_eq!(a.into_sorted_vec(), [-20, -10, 1, 2, 3, 3, 5, 43]);
578 /// assert!(b.is_empty());
580 #[stable(feature = "binary_heap_append", since = "1.11.0")]
581 pub fn append(&mut self, other: &mut Self) {
582 if self.len() < other.len() {
586 if other.is_empty() {
591 fn log2_fast(x: usize) -> usize {
592 8 * size_of::<usize>() - (x.leading_zeros() as usize) - 1
595 // `rebuild` takes O(len1 + len2) operations
596 // and about 2 * (len1 + len2) comparisons in the worst case
597 // while `extend` takes O(len2 * log_2(len1)) operations
598 // and about 1 * len2 * log_2(len1) comparisons in the worst case,
599 // assuming len1 >= len2.
601 fn better_to_rebuild(len1: usize, len2: usize) -> bool {
602 2 * (len1 + len2) < len2 * log2_fast(len1)
605 if better_to_rebuild(self.len(), other.len()) {
606 self.data.append(&mut other.data);
609 self.extend(other.drain());
614 impl<T> BinaryHeap<T> {
615 /// Returns an iterator visiting all values in the underlying vector, in
623 /// use std::collections::BinaryHeap;
624 /// let heap = BinaryHeap::from(vec![1, 2, 3, 4]);
626 /// // Print 1, 2, 3, 4 in arbitrary order
627 /// for x in heap.iter() {
628 /// println!("{}", x);
631 #[stable(feature = "rust1", since = "1.0.0")]
632 pub fn iter(&self) -> Iter<'_, T> {
633 Iter { iter: self.data.iter() }
636 /// Returns the greatest item in the binary heap, or `None` if it is empty.
643 /// use std::collections::BinaryHeap;
644 /// let mut heap = BinaryHeap::new();
645 /// assert_eq!(heap.peek(), None);
650 /// assert_eq!(heap.peek(), Some(&5));
653 #[stable(feature = "rust1", since = "1.0.0")]
654 pub fn peek(&self) -> Option<&T> {
658 /// Returns the number of elements the binary heap can hold without reallocating.
665 /// use std::collections::BinaryHeap;
666 /// let mut heap = BinaryHeap::with_capacity(100);
667 /// assert!(heap.capacity() >= 100);
670 #[stable(feature = "rust1", since = "1.0.0")]
671 pub fn capacity(&self) -> usize {
675 /// Reserves the minimum capacity for exactly `additional` more elements to be inserted in the
676 /// given `BinaryHeap`. Does nothing if the capacity is already sufficient.
678 /// Note that the allocator may give the collection more space than it requests. Therefore
679 /// capacity can not be relied upon to be precisely minimal. Prefer [`reserve`] if future
680 /// insertions are expected.
684 /// Panics if the new capacity overflows `usize`.
691 /// use std::collections::BinaryHeap;
692 /// let mut heap = BinaryHeap::new();
693 /// heap.reserve_exact(100);
694 /// assert!(heap.capacity() >= 100);
698 /// [`reserve`]: #method.reserve
699 #[stable(feature = "rust1", since = "1.0.0")]
700 pub fn reserve_exact(&mut self, additional: usize) {
701 self.data.reserve_exact(additional);
704 /// Reserves capacity for at least `additional` more elements to be inserted in the
705 /// `BinaryHeap`. The collection may reserve more space to avoid frequent reallocations.
709 /// Panics if the new capacity overflows `usize`.
716 /// use std::collections::BinaryHeap;
717 /// let mut heap = BinaryHeap::new();
718 /// heap.reserve(100);
719 /// assert!(heap.capacity() >= 100);
722 #[stable(feature = "rust1", since = "1.0.0")]
723 pub fn reserve(&mut self, additional: usize) {
724 self.data.reserve(additional);
727 /// Discards as much additional capacity as possible.
734 /// use std::collections::BinaryHeap;
735 /// let mut heap: BinaryHeap<i32> = BinaryHeap::with_capacity(100);
737 /// assert!(heap.capacity() >= 100);
738 /// heap.shrink_to_fit();
739 /// assert!(heap.capacity() == 0);
741 #[stable(feature = "rust1", since = "1.0.0")]
742 pub fn shrink_to_fit(&mut self) {
743 self.data.shrink_to_fit();
746 /// Discards capacity with a lower bound.
748 /// The capacity will remain at least as large as both the length
749 /// and the supplied value.
751 /// Panics if the current capacity is smaller than the supplied
752 /// minimum capacity.
757 /// #![feature(shrink_to)]
758 /// use std::collections::BinaryHeap;
759 /// let mut heap: BinaryHeap<i32> = BinaryHeap::with_capacity(100);
761 /// assert!(heap.capacity() >= 100);
762 /// heap.shrink_to(10);
763 /// assert!(heap.capacity() >= 10);
766 #[unstable(feature = "shrink_to", reason = "new API", issue="56431")]
767 pub fn shrink_to(&mut self, min_capacity: usize) {
768 self.data.shrink_to(min_capacity)
771 /// Consumes the `BinaryHeap` and returns the underlying vector
772 /// in arbitrary order.
779 /// use std::collections::BinaryHeap;
780 /// let heap = BinaryHeap::from(vec![1, 2, 3, 4, 5, 6, 7]);
781 /// let vec = heap.into_vec();
783 /// // Will print in some order
785 /// println!("{}", x);
788 #[stable(feature = "binary_heap_extras_15", since = "1.5.0")]
789 pub fn into_vec(self) -> Vec<T> {
793 /// Returns the length of the binary heap.
800 /// use std::collections::BinaryHeap;
801 /// let heap = BinaryHeap::from(vec![1, 3]);
803 /// assert_eq!(heap.len(), 2);
805 #[stable(feature = "rust1", since = "1.0.0")]
806 pub fn len(&self) -> usize {
810 /// Checks if the binary heap is empty.
817 /// use std::collections::BinaryHeap;
818 /// let mut heap = BinaryHeap::new();
820 /// assert!(heap.is_empty());
826 /// assert!(!heap.is_empty());
828 #[stable(feature = "rust1", since = "1.0.0")]
829 pub fn is_empty(&self) -> bool {
833 /// Clears the binary heap, returning an iterator over the removed elements.
835 /// The elements are removed in arbitrary order.
842 /// use std::collections::BinaryHeap;
843 /// let mut heap = BinaryHeap::from(vec![1, 3]);
845 /// assert!(!heap.is_empty());
847 /// for x in heap.drain() {
848 /// println!("{}", x);
851 /// assert!(heap.is_empty());
854 #[stable(feature = "drain", since = "1.6.0")]
855 pub fn drain(&mut self) -> Drain<'_, T> {
856 Drain { iter: self.data.drain(..) }
859 /// Drops all items from the binary heap.
866 /// use std::collections::BinaryHeap;
867 /// let mut heap = BinaryHeap::from(vec![1, 3]);
869 /// assert!(!heap.is_empty());
873 /// assert!(heap.is_empty());
875 #[stable(feature = "rust1", since = "1.0.0")]
876 pub fn clear(&mut self) {
881 /// Hole represents a hole in a slice i.e., an index without valid value
882 /// (because it was moved from or duplicated).
883 /// In drop, `Hole` will restore the slice by filling the hole
884 /// position with the value that was originally removed.
885 struct Hole<'a, T: 'a> {
887 elt: ManuallyDrop<T>,
891 impl<'a, T> Hole<'a, T> {
892 /// Create a new `Hole` at index `pos`.
894 /// Unsafe because pos must be within the data slice.
896 unsafe fn new(data: &'a mut [T], pos: usize) -> Self {
897 debug_assert!(pos < data.len());
898 // SAFE: pos should be inside the slice
899 let elt = ptr::read(data.get_unchecked(pos));
902 elt: ManuallyDrop::new(elt),
908 fn pos(&self) -> usize {
912 /// Returns a reference to the element removed.
914 fn element(&self) -> &T {
918 /// Returns a reference to the element at `index`.
920 /// Unsafe because index must be within the data slice and not equal to pos.
922 unsafe fn get(&self, index: usize) -> &T {
923 debug_assert!(index != self.pos);
924 debug_assert!(index < self.data.len());
925 self.data.get_unchecked(index)
928 /// Move hole to new location
930 /// Unsafe because index must be within the data slice and not equal to pos.
932 unsafe fn move_to(&mut self, index: usize) {
933 debug_assert!(index != self.pos);
934 debug_assert!(index < self.data.len());
935 let index_ptr: *const _ = self.data.get_unchecked(index);
936 let hole_ptr = self.data.get_unchecked_mut(self.pos);
937 ptr::copy_nonoverlapping(index_ptr, hole_ptr, 1);
942 impl<T> Drop for Hole<'_, T> {
945 // fill the hole again
948 ptr::copy_nonoverlapping(&*self.elt, self.data.get_unchecked_mut(pos), 1);
953 /// An iterator over the elements of a `BinaryHeap`.
955 /// This `struct` is created by the [`iter`] method on [`BinaryHeap`]. See its
956 /// documentation for more.
958 /// [`iter`]: struct.BinaryHeap.html#method.iter
959 /// [`BinaryHeap`]: struct.BinaryHeap.html
960 #[stable(feature = "rust1", since = "1.0.0")]
961 pub struct Iter<'a, T: 'a> {
962 iter: slice::Iter<'a, T>,
965 #[stable(feature = "collection_debug", since = "1.17.0")]
966 impl<T: fmt::Debug> fmt::Debug for Iter<'_, T> {
967 fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
968 f.debug_tuple("Iter")
969 .field(&self.iter.as_slice())
974 // FIXME(#26925) Remove in favor of `#[derive(Clone)]`
975 #[stable(feature = "rust1", since = "1.0.0")]
976 impl<T> Clone for Iter<'_, T> {
977 fn clone(&self) -> Self {
978 Iter { iter: self.iter.clone() }
982 #[stable(feature = "rust1", since = "1.0.0")]
983 impl<'a, T> Iterator for Iter<'a, T> {
987 fn next(&mut self) -> Option<&'a T> {
992 fn size_hint(&self) -> (usize, Option<usize>) {
993 self.iter.size_hint()
997 fn last(mut self) -> Option<&'a T> {
1002 #[stable(feature = "rust1", since = "1.0.0")]
1003 impl<'a, T> DoubleEndedIterator for Iter<'a, T> {
1005 fn next_back(&mut self) -> Option<&'a T> {
1006 self.iter.next_back()
1010 #[stable(feature = "rust1", since = "1.0.0")]
1011 impl<T> ExactSizeIterator for Iter<'_, T> {
1012 fn is_empty(&self) -> bool {
1013 self.iter.is_empty()
1017 #[stable(feature = "fused", since = "1.26.0")]
1018 impl<T> FusedIterator for Iter<'_, T> {}
1020 /// An owning iterator over the elements of a `BinaryHeap`.
1022 /// This `struct` is created by the [`into_iter`] method on [`BinaryHeap`][`BinaryHeap`]
1023 /// (provided by the `IntoIterator` trait). See its documentation for more.
1025 /// [`into_iter`]: struct.BinaryHeap.html#method.into_iter
1026 /// [`BinaryHeap`]: struct.BinaryHeap.html
1027 #[stable(feature = "rust1", since = "1.0.0")]
1029 pub struct IntoIter<T> {
1030 iter: vec::IntoIter<T>,
1033 #[stable(feature = "collection_debug", since = "1.17.0")]
1034 impl<T: fmt::Debug> fmt::Debug for IntoIter<T> {
1035 fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
1036 f.debug_tuple("IntoIter")
1037 .field(&self.iter.as_slice())
1042 #[stable(feature = "rust1", since = "1.0.0")]
1043 impl<T> Iterator for IntoIter<T> {
1047 fn next(&mut self) -> Option<T> {
1052 fn size_hint(&self) -> (usize, Option<usize>) {
1053 self.iter.size_hint()
1057 fn last(mut self) -> Option<T> {
1062 #[stable(feature = "rust1", since = "1.0.0")]
1063 impl<T> DoubleEndedIterator for IntoIter<T> {
1065 fn next_back(&mut self) -> Option<T> {
1066 self.iter.next_back()
1070 #[stable(feature = "rust1", since = "1.0.0")]
1071 impl<T> ExactSizeIterator for IntoIter<T> {
1072 fn is_empty(&self) -> bool {
1073 self.iter.is_empty()
1077 #[stable(feature = "fused", since = "1.26.0")]
1078 impl<T> FusedIterator for IntoIter<T> {}
1080 /// A draining iterator over the elements of a `BinaryHeap`.
1082 /// This `struct` is created by the [`drain`] method on [`BinaryHeap`]. See its
1083 /// documentation for more.
1085 /// [`drain`]: struct.BinaryHeap.html#method.drain
1086 /// [`BinaryHeap`]: struct.BinaryHeap.html
1087 #[stable(feature = "drain", since = "1.6.0")]
1089 pub struct Drain<'a, T: 'a> {
1090 iter: vec::Drain<'a, T>,
1093 #[stable(feature = "drain", since = "1.6.0")]
1094 impl<T> Iterator for Drain<'_, T> {
1098 fn next(&mut self) -> Option<T> {
1103 fn size_hint(&self) -> (usize, Option<usize>) {
1104 self.iter.size_hint()
1108 fn last(mut self) -> Option<T> {
1113 #[stable(feature = "drain", since = "1.6.0")]
1114 impl<T> DoubleEndedIterator for Drain<'_, T> {
1116 fn next_back(&mut self) -> Option<T> {
1117 self.iter.next_back()
1121 #[stable(feature = "drain", since = "1.6.0")]
1122 impl<T> ExactSizeIterator for Drain<'_, T> {
1123 fn is_empty(&self) -> bool {
1124 self.iter.is_empty()
1128 #[stable(feature = "fused", since = "1.26.0")]
1129 impl<T> FusedIterator for Drain<'_, T> {}
1131 #[stable(feature = "binary_heap_extras_15", since = "1.5.0")]
1132 impl<T: Ord> From<Vec<T>> for BinaryHeap<T> {
1133 fn from(vec: Vec<T>) -> BinaryHeap<T> {
1134 let mut heap = BinaryHeap { data: vec };
1140 #[stable(feature = "binary_heap_extras_15", since = "1.5.0")]
1141 impl<T> From<BinaryHeap<T>> for Vec<T> {
1142 fn from(heap: BinaryHeap<T>) -> Vec<T> {
1147 #[stable(feature = "rust1", since = "1.0.0")]
1148 impl<T: Ord> FromIterator<T> for BinaryHeap<T> {
1149 fn from_iter<I: IntoIterator<Item = T>>(iter: I) -> BinaryHeap<T> {
1150 BinaryHeap::from(iter.into_iter().collect::<Vec<_>>())
1154 #[stable(feature = "rust1", since = "1.0.0")]
1155 impl<T> IntoIterator for BinaryHeap<T> {
1157 type IntoIter = IntoIter<T>;
1159 /// Creates a consuming iterator, that is, one that moves each value out of
1160 /// the binary heap in arbitrary order. The binary heap cannot be used
1161 /// after calling this.
1168 /// use std::collections::BinaryHeap;
1169 /// let heap = BinaryHeap::from(vec![1, 2, 3, 4]);
1171 /// // Print 1, 2, 3, 4 in arbitrary order
1172 /// for x in heap.into_iter() {
1173 /// // x has type i32, not &i32
1174 /// println!("{}", x);
1177 fn into_iter(self) -> IntoIter<T> {
1178 IntoIter { iter: self.data.into_iter() }
1182 #[stable(feature = "rust1", since = "1.0.0")]
1183 impl<'a, T> IntoIterator for &'a BinaryHeap<T> {
1185 type IntoIter = Iter<'a, T>;
1187 fn into_iter(self) -> Iter<'a, T> {
1192 #[stable(feature = "rust1", since = "1.0.0")]
1193 impl<T: Ord> Extend<T> for BinaryHeap<T> {
1195 fn extend<I: IntoIterator<Item = T>>(&mut self, iter: I) {
1196 <Self as SpecExtend<I>>::spec_extend(self, iter);
1200 impl<T: Ord, I: IntoIterator<Item = T>> SpecExtend<I> for BinaryHeap<T> {
1201 default fn spec_extend(&mut self, iter: I) {
1202 self.extend_desugared(iter.into_iter());
1206 impl<T: Ord> SpecExtend<BinaryHeap<T>> for BinaryHeap<T> {
1207 fn spec_extend(&mut self, ref mut other: BinaryHeap<T>) {
1212 impl<T: Ord> BinaryHeap<T> {
1213 fn extend_desugared<I: IntoIterator<Item = T>>(&mut self, iter: I) {
1214 let iterator = iter.into_iter();
1215 let (lower, _) = iterator.size_hint();
1217 self.reserve(lower);
1219 iterator.for_each(move |elem| self.push(elem));
1223 #[stable(feature = "extend_ref", since = "1.2.0")]
1224 impl<'a, T: 'a + Ord + Copy> Extend<&'a T> for BinaryHeap<T> {
1225 fn extend<I: IntoIterator<Item = &'a T>>(&mut self, iter: I) {
1226 self.extend(iter.into_iter().cloned());