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())
210 #[stable(feature = "rust1", since = "1.0.0")]
211 pub struct BinaryHeap<T> {
215 /// Structure wrapping a mutable reference to the greatest item on a
218 /// This `struct` is created by the [`peek_mut`] method on [`BinaryHeap`]. See
219 /// its documentation for more.
221 /// [`peek_mut`]: struct.BinaryHeap.html#method.peek_mut
222 /// [`BinaryHeap`]: struct.BinaryHeap.html
223 #[stable(feature = "binary_heap_peek_mut", since = "1.12.0")]
224 pub struct PeekMut<'a, T: 'a + Ord> {
225 heap: &'a mut BinaryHeap<T>,
229 #[stable(feature = "collection_debug", since = "1.17.0")]
230 impl<T: Ord + fmt::Debug> fmt::Debug for PeekMut<'_, T> {
231 fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
232 f.debug_tuple("PeekMut")
233 .field(&self.heap.data[0])
238 #[stable(feature = "binary_heap_peek_mut", since = "1.12.0")]
239 impl<T: Ord> Drop for PeekMut<'_, T> {
242 self.heap.sift_down(0);
247 #[stable(feature = "binary_heap_peek_mut", since = "1.12.0")]
248 impl<T: Ord> Deref for PeekMut<'_, T> {
250 fn deref(&self) -> &T {
251 debug_assert!(!self.heap.is_empty());
252 // SAFE: PeekMut is only instantiated for non-empty heaps
253 unsafe { self.heap.data.get_unchecked(0) }
257 #[stable(feature = "binary_heap_peek_mut", since = "1.12.0")]
258 impl<T: Ord> DerefMut for PeekMut<'_, T> {
259 fn deref_mut(&mut self) -> &mut T {
260 debug_assert!(!self.heap.is_empty());
261 // SAFE: PeekMut is only instantiated for non-empty heaps
262 unsafe { self.heap.data.get_unchecked_mut(0) }
266 impl<'a, T: Ord> PeekMut<'a, T> {
267 /// Removes the peeked value from the heap and returns it.
268 #[stable(feature = "binary_heap_peek_mut_pop", since = "1.18.0")]
269 pub fn pop(mut this: PeekMut<'a, T>) -> T {
270 let value = this.heap.pop().unwrap();
276 #[stable(feature = "rust1", since = "1.0.0")]
277 impl<T: Clone> Clone for BinaryHeap<T> {
278 fn clone(&self) -> Self {
279 BinaryHeap { data: self.data.clone() }
282 fn clone_from(&mut self, source: &Self) {
283 self.data.clone_from(&source.data);
287 #[stable(feature = "rust1", since = "1.0.0")]
288 impl<T: Ord> Default for BinaryHeap<T> {
289 /// Creates an empty `BinaryHeap<T>`.
291 fn default() -> BinaryHeap<T> {
296 #[stable(feature = "binaryheap_debug", since = "1.4.0")]
297 impl<T: fmt::Debug + Ord> fmt::Debug for BinaryHeap<T> {
298 fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
299 f.debug_list().entries(self.iter()).finish()
303 impl<T: Ord> BinaryHeap<T> {
304 /// Creates an empty `BinaryHeap` as a max-heap.
311 /// use std::collections::BinaryHeap;
312 /// let mut heap = BinaryHeap::new();
315 #[stable(feature = "rust1", since = "1.0.0")]
316 pub fn new() -> BinaryHeap<T> {
317 BinaryHeap { data: vec![] }
320 /// Creates an empty `BinaryHeap` with a specific capacity.
321 /// This preallocates enough memory for `capacity` elements,
322 /// so that the `BinaryHeap` does not have to be reallocated
323 /// until it contains at least that many values.
330 /// use std::collections::BinaryHeap;
331 /// let mut heap = BinaryHeap::with_capacity(10);
334 #[stable(feature = "rust1", since = "1.0.0")]
335 pub fn with_capacity(capacity: usize) -> BinaryHeap<T> {
336 BinaryHeap { data: Vec::with_capacity(capacity) }
339 /// Returns an iterator visiting all values in the underlying vector, in
347 /// use std::collections::BinaryHeap;
348 /// let heap = BinaryHeap::from(vec![1, 2, 3, 4]);
350 /// // Print 1, 2, 3, 4 in arbitrary order
351 /// for x in heap.iter() {
352 /// println!("{}", x);
355 #[stable(feature = "rust1", since = "1.0.0")]
356 pub fn iter(&self) -> Iter<'_, T> {
357 Iter { iter: self.data.iter() }
360 /// Returns the greatest item in the binary heap, or `None` if it is empty.
367 /// use std::collections::BinaryHeap;
368 /// let mut heap = BinaryHeap::new();
369 /// assert_eq!(heap.peek(), None);
374 /// assert_eq!(heap.peek(), Some(&5));
377 #[stable(feature = "rust1", since = "1.0.0")]
378 pub fn peek(&self) -> Option<&T> {
382 /// Returns a mutable reference to the greatest item in the binary heap, or
383 /// `None` if it is empty.
385 /// Note: If the `PeekMut` value is leaked, the heap may be in an
386 /// inconsistent state.
393 /// use std::collections::BinaryHeap;
394 /// let mut heap = BinaryHeap::new();
395 /// assert!(heap.peek_mut().is_none());
401 /// let mut val = heap.peek_mut().unwrap();
404 /// assert_eq!(heap.peek(), Some(&2));
406 #[stable(feature = "binary_heap_peek_mut", since = "1.12.0")]
407 pub fn peek_mut(&mut self) -> Option<PeekMut<'_, T>> {
418 /// Returns the number of elements the binary heap can hold without reallocating.
425 /// use std::collections::BinaryHeap;
426 /// let mut heap = BinaryHeap::with_capacity(100);
427 /// assert!(heap.capacity() >= 100);
430 #[stable(feature = "rust1", since = "1.0.0")]
431 pub fn capacity(&self) -> usize {
435 /// Reserves the minimum capacity for exactly `additional` more elements to be inserted in the
436 /// given `BinaryHeap`. Does nothing if the capacity is already sufficient.
438 /// Note that the allocator may give the collection more space than it requests. Therefore
439 /// capacity can not be relied upon to be precisely minimal. Prefer [`reserve`] if future
440 /// insertions are expected.
444 /// Panics if the new capacity overflows `usize`.
451 /// use std::collections::BinaryHeap;
452 /// let mut heap = BinaryHeap::new();
453 /// heap.reserve_exact(100);
454 /// assert!(heap.capacity() >= 100);
458 /// [`reserve`]: #method.reserve
459 #[stable(feature = "rust1", since = "1.0.0")]
460 pub fn reserve_exact(&mut self, additional: usize) {
461 self.data.reserve_exact(additional);
464 /// Reserves capacity for at least `additional` more elements to be inserted in the
465 /// `BinaryHeap`. The collection may reserve more space to avoid frequent reallocations.
469 /// Panics if the new capacity overflows `usize`.
476 /// use std::collections::BinaryHeap;
477 /// let mut heap = BinaryHeap::new();
478 /// heap.reserve(100);
479 /// assert!(heap.capacity() >= 100);
482 #[stable(feature = "rust1", since = "1.0.0")]
483 pub fn reserve(&mut self, additional: usize) {
484 self.data.reserve(additional);
487 /// Discards as much additional capacity as possible.
494 /// use std::collections::BinaryHeap;
495 /// let mut heap: BinaryHeap<i32> = BinaryHeap::with_capacity(100);
497 /// assert!(heap.capacity() >= 100);
498 /// heap.shrink_to_fit();
499 /// assert!(heap.capacity() == 0);
501 #[stable(feature = "rust1", since = "1.0.0")]
502 pub fn shrink_to_fit(&mut self) {
503 self.data.shrink_to_fit();
506 /// Discards capacity with a lower bound.
508 /// The capacity will remain at least as large as both the length
509 /// and the supplied value.
511 /// Panics if the current capacity is smaller than the supplied
512 /// minimum capacity.
517 /// #![feature(shrink_to)]
518 /// use std::collections::BinaryHeap;
519 /// let mut heap: BinaryHeap<i32> = BinaryHeap::with_capacity(100);
521 /// assert!(heap.capacity() >= 100);
522 /// heap.shrink_to(10);
523 /// assert!(heap.capacity() >= 10);
526 #[unstable(feature = "shrink_to", reason = "new API", issue="56431")]
527 pub fn shrink_to(&mut self, min_capacity: usize) {
528 self.data.shrink_to(min_capacity)
531 /// Removes the greatest item from the binary heap and returns it, or `None` if it
539 /// use std::collections::BinaryHeap;
540 /// let mut heap = BinaryHeap::from(vec![1, 3]);
542 /// assert_eq!(heap.pop(), Some(3));
543 /// assert_eq!(heap.pop(), Some(1));
544 /// assert_eq!(heap.pop(), None);
546 #[stable(feature = "rust1", since = "1.0.0")]
547 pub fn pop(&mut self) -> Option<T> {
548 self.data.pop().map(|mut item| {
549 if !self.is_empty() {
550 swap(&mut item, &mut self.data[0]);
551 self.sift_down_to_bottom(0);
557 /// Pushes an item onto the binary heap.
564 /// use std::collections::BinaryHeap;
565 /// let mut heap = BinaryHeap::new();
570 /// assert_eq!(heap.len(), 3);
571 /// assert_eq!(heap.peek(), Some(&5));
573 #[stable(feature = "rust1", since = "1.0.0")]
574 pub fn push(&mut self, item: T) {
575 let old_len = self.len();
576 self.data.push(item);
577 self.sift_up(0, old_len);
580 /// Consumes the `BinaryHeap` and returns the underlying vector
581 /// in arbitrary order.
588 /// use std::collections::BinaryHeap;
589 /// let heap = BinaryHeap::from(vec![1, 2, 3, 4, 5, 6, 7]);
590 /// let vec = heap.into_vec();
592 /// // Will print in some order
594 /// println!("{}", x);
597 #[stable(feature = "binary_heap_extras_15", since = "1.5.0")]
598 pub fn into_vec(self) -> Vec<T> {
602 /// Consumes the `BinaryHeap` and returns a vector in sorted
603 /// (ascending) order.
610 /// use std::collections::BinaryHeap;
612 /// let mut heap = BinaryHeap::from(vec![1, 2, 4, 5, 7]);
616 /// let vec = heap.into_sorted_vec();
617 /// assert_eq!(vec, [1, 2, 3, 4, 5, 6, 7]);
619 #[stable(feature = "binary_heap_extras_15", since = "1.5.0")]
620 pub fn into_sorted_vec(mut self) -> Vec<T> {
621 let mut end = self.len();
624 self.data.swap(0, end);
625 self.sift_down_range(0, end);
630 // The implementations of sift_up and sift_down use unsafe blocks in
631 // order to move an element out of the vector (leaving behind a
632 // hole), shift along the others and move the removed element back into the
633 // vector at the final location of the hole.
634 // The `Hole` type is used to represent this, and make sure
635 // the hole is filled back at the end of its scope, even on panic.
636 // Using a hole reduces the constant factor compared to using swaps,
637 // which involves twice as many moves.
638 fn sift_up(&mut self, start: usize, pos: usize) -> usize {
640 // Take out the value at `pos` and create a hole.
641 let mut hole = Hole::new(&mut self.data, pos);
643 while hole.pos() > start {
644 let parent = (hole.pos() - 1) / 2;
645 if hole.element() <= hole.get(parent) {
648 hole.move_to(parent);
654 /// Take an element at `pos` and move it down the heap,
655 /// while its children are larger.
656 fn sift_down_range(&mut self, pos: usize, end: usize) {
658 let mut hole = Hole::new(&mut self.data, pos);
659 let mut child = 2 * pos + 1;
661 let right = child + 1;
662 // compare with the greater of the two children
663 if right < end && !(hole.get(child) > hole.get(right)) {
666 // if we are already in order, stop.
667 if hole.element() >= hole.get(child) {
671 child = 2 * hole.pos() + 1;
676 fn sift_down(&mut self, pos: usize) {
677 let len = self.len();
678 self.sift_down_range(pos, len);
681 /// Take an element at `pos` and move it all the way down the heap,
682 /// then sift it up to its position.
684 /// Note: This is faster when the element is known to be large / should
685 /// be closer to the bottom.
686 fn sift_down_to_bottom(&mut self, mut pos: usize) {
687 let end = self.len();
690 let mut hole = Hole::new(&mut self.data, pos);
691 let mut child = 2 * pos + 1;
693 let right = child + 1;
694 // compare with the greater of the two children
695 if right < end && !(hole.get(child) > hole.get(right)) {
699 child = 2 * hole.pos() + 1;
703 self.sift_up(start, pos);
706 /// Returns the length of the binary heap.
713 /// use std::collections::BinaryHeap;
714 /// let heap = BinaryHeap::from(vec![1, 3]);
716 /// assert_eq!(heap.len(), 2);
718 #[stable(feature = "rust1", since = "1.0.0")]
719 pub fn len(&self) -> usize {
723 /// Checks if the binary heap is empty.
730 /// use std::collections::BinaryHeap;
731 /// let mut heap = BinaryHeap::new();
733 /// assert!(heap.is_empty());
739 /// assert!(!heap.is_empty());
741 #[stable(feature = "rust1", since = "1.0.0")]
742 pub fn is_empty(&self) -> bool {
746 /// Clears the binary heap, returning an iterator over the removed elements.
748 /// The elements are removed in arbitrary order.
755 /// use std::collections::BinaryHeap;
756 /// let mut heap = BinaryHeap::from(vec![1, 3]);
758 /// assert!(!heap.is_empty());
760 /// for x in heap.drain() {
761 /// println!("{}", x);
764 /// assert!(heap.is_empty());
767 #[stable(feature = "drain", since = "1.6.0")]
768 pub fn drain(&mut self) -> Drain<'_, T> {
769 Drain { iter: self.data.drain(..) }
772 /// Drops all items from the binary heap.
779 /// use std::collections::BinaryHeap;
780 /// let mut heap = BinaryHeap::from(vec![1, 3]);
782 /// assert!(!heap.is_empty());
786 /// assert!(heap.is_empty());
788 #[stable(feature = "rust1", since = "1.0.0")]
789 pub fn clear(&mut self) {
793 fn rebuild(&mut self) {
794 let mut n = self.len() / 2;
801 /// Moves all the elements of `other` into `self`, leaving `other` empty.
808 /// use std::collections::BinaryHeap;
810 /// let v = vec![-10, 1, 2, 3, 3];
811 /// let mut a = BinaryHeap::from(v);
813 /// let v = vec![-20, 5, 43];
814 /// let mut b = BinaryHeap::from(v);
816 /// a.append(&mut b);
818 /// assert_eq!(a.into_sorted_vec(), [-20, -10, 1, 2, 3, 3, 5, 43]);
819 /// assert!(b.is_empty());
821 #[stable(feature = "binary_heap_append", since = "1.11.0")]
822 pub fn append(&mut self, other: &mut Self) {
823 if self.len() < other.len() {
827 if other.is_empty() {
832 fn log2_fast(x: usize) -> usize {
833 8 * size_of::<usize>() - (x.leading_zeros() as usize) - 1
836 // `rebuild` takes O(len1 + len2) operations
837 // and about 2 * (len1 + len2) comparisons in the worst case
838 // while `extend` takes O(len2 * log_2(len1)) operations
839 // and about 1 * len2 * log_2(len1) comparisons in the worst case,
840 // assuming len1 >= len2.
842 fn better_to_rebuild(len1: usize, len2: usize) -> bool {
843 2 * (len1 + len2) < len2 * log2_fast(len1)
846 if better_to_rebuild(self.len(), other.len()) {
847 self.data.append(&mut other.data);
850 self.extend(other.drain());
855 /// Hole represents a hole in a slice i.e., an index without valid value
856 /// (because it was moved from or duplicated).
857 /// In drop, `Hole` will restore the slice by filling the hole
858 /// position with the value that was originally removed.
859 struct Hole<'a, T: 'a> {
861 elt: ManuallyDrop<T>,
865 impl<'a, T> Hole<'a, T> {
866 /// Create a new Hole at index `pos`.
868 /// Unsafe because pos must be within the data slice.
870 unsafe fn new(data: &'a mut [T], pos: usize) -> Self {
871 debug_assert!(pos < data.len());
872 // SAFE: pos should be inside the slice
873 let elt = ptr::read(data.get_unchecked(pos));
876 elt: ManuallyDrop::new(elt),
882 fn pos(&self) -> usize {
886 /// Returns a reference to the element removed.
888 fn element(&self) -> &T {
892 /// Returns a reference to the element at `index`.
894 /// Unsafe because index must be within the data slice and not equal to pos.
896 unsafe fn get(&self, index: usize) -> &T {
897 debug_assert!(index != self.pos);
898 debug_assert!(index < self.data.len());
899 self.data.get_unchecked(index)
902 /// Move hole to new location
904 /// Unsafe because index must be within the data slice and not equal to pos.
906 unsafe fn move_to(&mut self, index: usize) {
907 debug_assert!(index != self.pos);
908 debug_assert!(index < self.data.len());
909 let index_ptr: *const _ = self.data.get_unchecked(index);
910 let hole_ptr = self.data.get_unchecked_mut(self.pos);
911 ptr::copy_nonoverlapping(index_ptr, hole_ptr, 1);
916 impl<T> Drop for Hole<'_, T> {
919 // fill the hole again
922 ptr::copy_nonoverlapping(&*self.elt, self.data.get_unchecked_mut(pos), 1);
927 /// An iterator over the elements of a `BinaryHeap`.
929 /// This `struct` is created by the [`iter`] method on [`BinaryHeap`]. See its
930 /// documentation for more.
932 /// [`iter`]: struct.BinaryHeap.html#method.iter
933 /// [`BinaryHeap`]: struct.BinaryHeap.html
934 #[stable(feature = "rust1", since = "1.0.0")]
935 pub struct Iter<'a, T: 'a> {
936 iter: slice::Iter<'a, T>,
939 #[stable(feature = "collection_debug", since = "1.17.0")]
940 impl<T: fmt::Debug> fmt::Debug for Iter<'_, T> {
941 fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
942 f.debug_tuple("Iter")
943 .field(&self.iter.as_slice())
948 // FIXME(#26925) Remove in favor of `#[derive(Clone)]`
949 #[stable(feature = "rust1", since = "1.0.0")]
950 impl<'a, T> Clone for Iter<'a, T> {
951 fn clone(&self) -> Iter<'a, T> {
952 Iter { iter: self.iter.clone() }
956 #[stable(feature = "rust1", since = "1.0.0")]
957 impl<'a, T> Iterator for Iter<'a, T> {
961 fn next(&mut self) -> Option<&'a T> {
966 fn size_hint(&self) -> (usize, Option<usize>) {
967 self.iter.size_hint()
971 #[stable(feature = "rust1", since = "1.0.0")]
972 impl<'a, T> DoubleEndedIterator for Iter<'a, T> {
974 fn next_back(&mut self) -> Option<&'a T> {
975 self.iter.next_back()
979 #[stable(feature = "rust1", since = "1.0.0")]
980 impl<T> ExactSizeIterator for Iter<'_, T> {
981 fn is_empty(&self) -> bool {
986 #[stable(feature = "fused", since = "1.26.0")]
987 impl<T> FusedIterator for Iter<'_, T> {}
989 /// An owning iterator over the elements of a `BinaryHeap`.
991 /// This `struct` is created by the [`into_iter`] method on [`BinaryHeap`][`BinaryHeap`]
992 /// (provided by the `IntoIterator` trait). See its documentation for more.
994 /// [`into_iter`]: struct.BinaryHeap.html#method.into_iter
995 /// [`BinaryHeap`]: struct.BinaryHeap.html
996 #[stable(feature = "rust1", since = "1.0.0")]
998 pub struct IntoIter<T> {
999 iter: vec::IntoIter<T>,
1002 #[stable(feature = "collection_debug", since = "1.17.0")]
1003 impl<T: fmt::Debug> fmt::Debug for IntoIter<T> {
1004 fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
1005 f.debug_tuple("IntoIter")
1006 .field(&self.iter.as_slice())
1011 #[stable(feature = "rust1", since = "1.0.0")]
1012 impl<T> Iterator for IntoIter<T> {
1016 fn next(&mut self) -> Option<T> {
1021 fn size_hint(&self) -> (usize, Option<usize>) {
1022 self.iter.size_hint()
1026 #[stable(feature = "rust1", since = "1.0.0")]
1027 impl<T> DoubleEndedIterator for IntoIter<T> {
1029 fn next_back(&mut self) -> Option<T> {
1030 self.iter.next_back()
1034 #[stable(feature = "rust1", since = "1.0.0")]
1035 impl<T> ExactSizeIterator for IntoIter<T> {
1036 fn is_empty(&self) -> bool {
1037 self.iter.is_empty()
1041 #[stable(feature = "fused", since = "1.26.0")]
1042 impl<T> FusedIterator for IntoIter<T> {}
1044 /// A draining iterator over the elements of a `BinaryHeap`.
1046 /// This `struct` is created by the [`drain`] method on [`BinaryHeap`]. See its
1047 /// documentation for more.
1049 /// [`drain`]: struct.BinaryHeap.html#method.drain
1050 /// [`BinaryHeap`]: struct.BinaryHeap.html
1051 #[stable(feature = "drain", since = "1.6.0")]
1053 pub struct Drain<'a, T: 'a> {
1054 iter: vec::Drain<'a, T>,
1057 #[stable(feature = "drain", since = "1.6.0")]
1058 impl<T> Iterator for Drain<'_, T> {
1062 fn next(&mut self) -> Option<T> {
1067 fn size_hint(&self) -> (usize, Option<usize>) {
1068 self.iter.size_hint()
1072 #[stable(feature = "drain", since = "1.6.0")]
1073 impl<T> DoubleEndedIterator for Drain<'_, T> {
1075 fn next_back(&mut self) -> Option<T> {
1076 self.iter.next_back()
1080 #[stable(feature = "drain", since = "1.6.0")]
1081 impl<T> ExactSizeIterator for Drain<'_, T> {
1082 fn is_empty(&self) -> bool {
1083 self.iter.is_empty()
1087 #[stable(feature = "fused", since = "1.26.0")]
1088 impl<T> FusedIterator for Drain<'_, T> {}
1090 #[stable(feature = "binary_heap_extras_15", since = "1.5.0")]
1091 impl<T: Ord> From<Vec<T>> for BinaryHeap<T> {
1092 fn from(vec: Vec<T>) -> BinaryHeap<T> {
1093 let mut heap = BinaryHeap { data: vec };
1099 #[stable(feature = "binary_heap_extras_15", since = "1.5.0")]
1100 impl<T> From<BinaryHeap<T>> for Vec<T> {
1101 fn from(heap: BinaryHeap<T>) -> Vec<T> {
1106 #[stable(feature = "rust1", since = "1.0.0")]
1107 impl<T: Ord> FromIterator<T> for BinaryHeap<T> {
1108 fn from_iter<I: IntoIterator<Item = T>>(iter: I) -> BinaryHeap<T> {
1109 BinaryHeap::from(iter.into_iter().collect::<Vec<_>>())
1113 #[stable(feature = "rust1", since = "1.0.0")]
1114 impl<T: Ord> IntoIterator for BinaryHeap<T> {
1116 type IntoIter = IntoIter<T>;
1118 /// Creates a consuming iterator, that is, one that moves each value out of
1119 /// the binary heap in arbitrary order. The binary heap cannot be used
1120 /// after calling this.
1127 /// use std::collections::BinaryHeap;
1128 /// let heap = BinaryHeap::from(vec![1, 2, 3, 4]);
1130 /// // Print 1, 2, 3, 4 in arbitrary order
1131 /// for x in heap.into_iter() {
1132 /// // x has type i32, not &i32
1133 /// println!("{}", x);
1136 fn into_iter(self) -> IntoIter<T> {
1137 IntoIter { iter: self.data.into_iter() }
1141 #[stable(feature = "rust1", since = "1.0.0")]
1142 impl<'a, T> IntoIterator for &'a BinaryHeap<T>
1146 type IntoIter = Iter<'a, T>;
1148 fn into_iter(self) -> Iter<'a, T> {
1153 #[stable(feature = "rust1", since = "1.0.0")]
1154 impl<T: Ord> Extend<T> for BinaryHeap<T> {
1156 fn extend<I: IntoIterator<Item = T>>(&mut self, iter: I) {
1157 <Self as SpecExtend<I>>::spec_extend(self, iter);
1161 impl<T: Ord, I: IntoIterator<Item = T>> SpecExtend<I> for BinaryHeap<T> {
1162 default fn spec_extend(&mut self, iter: I) {
1163 self.extend_desugared(iter.into_iter());
1167 impl<T: Ord> SpecExtend<BinaryHeap<T>> for BinaryHeap<T> {
1168 fn spec_extend(&mut self, ref mut other: BinaryHeap<T>) {
1173 impl<T: Ord> BinaryHeap<T> {
1174 fn extend_desugared<I: IntoIterator<Item = T>>(&mut self, iter: I) {
1175 let iterator = iter.into_iter();
1176 let (lower, _) = iterator.size_hint();
1178 self.reserve(lower);
1180 for elem in iterator {
1186 #[stable(feature = "extend_ref", since = "1.2.0")]
1187 impl<'a, T: 'a + Ord + Copy> Extend<&'a T> for BinaryHeap<T> {
1188 fn extend<I: IntoIterator<Item = &'a T>>(&mut self, iter: I) {
1189 self.extend(iter.into_iter().cloned());