1 // Copyright 2013-2014 The Rust Project Developers. See the COPYRIGHT
2 // file at the top-level directory of this distribution and at
3 // http://rust-lang.org/COPYRIGHT.
5 // Licensed under the Apache License, Version 2.0 <LICENSE-APACHE or
6 // http://www.apache.org/licenses/LICENSE-2.0> or the MIT license
7 // <LICENSE-MIT or http://opensource.org/licenses/MIT>, at your
8 // option. This file may not be copied, modified, or distributed
9 // except according to those terms.
11 //! A priority queue implemented with a binary heap.
13 //! Insertion and popping the largest element have `O(log n)` time complexity.
14 //! Checking the largest element is `O(1)`. Converting a vector to a binary heap
15 //! can be done in-place, and has `O(n)` complexity. A binary heap can also be
16 //! converted to a sorted vector in-place, allowing it to be used for an `O(n
17 //! log n)` in-place heapsort.
21 //! This is a larger example that implements [Dijkstra's algorithm][dijkstra]
22 //! to solve the [shortest path problem][sssp] on a [directed graph][dir_graph].
23 //! It shows how to use `BinaryHeap` with custom types.
25 //! [dijkstra]: http://en.wikipedia.org/wiki/Dijkstra%27s_algorithm
26 //! [sssp]: http://en.wikipedia.org/wiki/Shortest_path_problem
27 //! [dir_graph]: http://en.wikipedia.org/wiki/Directed_graph
30 //! use std::cmp::Ordering;
31 //! use std::collections::BinaryHeap;
34 //! #[derive(Copy, Clone, Eq, PartialEq)]
40 //! // The priority queue depends on `Ord`.
41 //! // Explicitly implement the trait so the queue becomes a min-heap
42 //! // instead of a max-heap.
43 //! impl Ord for State {
44 //! fn cmp(&self, other: &State) -> Ordering {
45 //! // Notice that the we flip the ordering here
46 //! other.cost.cmp(&self.cost)
50 //! // `PartialOrd` needs to be implemented as well.
51 //! impl PartialOrd for State {
52 //! fn partial_cmp(&self, other: &State) -> Option<Ordering> {
53 //! Some(self.cmp(other))
57 //! // Each node is represented as an `usize`, for a shorter implementation.
63 //! // Dijkstra's shortest path algorithm.
65 //! // Start at `start` and use `dist` to track the current shortest distance
66 //! // to each node. This implementation isn't memory-efficient as it may leave duplicate
67 //! // nodes in the queue. It also uses `usize::MAX` as a sentinel value,
68 //! // for a simpler implementation.
69 //! fn shortest_path(adj_list: &Vec<Vec<Edge>>, start: usize, goal: usize) -> Option<usize> {
70 //! // dist[node] = current shortest distance from `start` to `node`
71 //! let mut dist: Vec<_> = (0..adj_list.len()).map(|_| usize::MAX).collect();
73 //! let mut heap = BinaryHeap::new();
75 //! // We're at `start`, with a zero cost
77 //! heap.push(State { cost: 0, position: start });
79 //! // Examine the frontier with lower cost nodes first (min-heap)
80 //! while let Some(State { cost, position }) = heap.pop() {
81 //! // Alternatively we could have continued to find all shortest paths
82 //! if position == goal { return Some(cost); }
84 //! // Important as we may have already found a better way
85 //! if cost > dist[position] { continue; }
87 //! // For each node we can reach, see if we can find a way with
88 //! // a lower cost going through this node
89 //! for edge in &adj_list[position] {
90 //! let next = State { cost: cost + edge.cost, position: edge.node };
92 //! // If so, add it to the frontier and continue
93 //! if next.cost < dist[next.position] {
95 //! // Relaxation, we have now found a better way
96 //! dist[next.position] = next.cost;
101 //! // Goal not reachable
106 //! // This is the directed graph we're going to use.
107 //! // The node numbers correspond to the different states,
108 //! // and the edge weights symbolize the cost of moving
109 //! // from one node to another.
110 //! // Note that the edges are one-way.
113 //! // +-----------------+
116 //! // 0 -----> 1 -----> 3 ---> 4
120 //! // +------> 2 -------+ |
122 //! // +---------------+
124 //! // The graph is represented as an adjacency list where each index,
125 //! // corresponding to a node value, has a list of outgoing edges.
126 //! // Chosen for its efficiency.
127 //! let graph = vec![
129 //! vec![Edge { node: 2, cost: 10 },
130 //! Edge { node: 1, cost: 1 }],
132 //! vec![Edge { node: 3, cost: 2 }],
134 //! vec![Edge { node: 1, cost: 1 },
135 //! Edge { node: 3, cost: 3 },
136 //! Edge { node: 4, cost: 1 }],
138 //! vec![Edge { node: 0, cost: 7 },
139 //! Edge { node: 4, cost: 2 }],
143 //! assert_eq!(shortest_path(&graph, 0, 1), Some(1));
144 //! assert_eq!(shortest_path(&graph, 0, 3), Some(3));
145 //! assert_eq!(shortest_path(&graph, 3, 0), Some(7));
146 //! assert_eq!(shortest_path(&graph, 0, 4), Some(5));
147 //! assert_eq!(shortest_path(&graph, 4, 0), None);
151 #![allow(missing_docs)]
152 #![stable(feature = "rust1", since = "1.0.0")]
154 use core::ops::{Drop, Deref, DerefMut};
155 use core::iter::{FromIterator, FusedIterator};
157 use core::mem::size_of;
162 use vec::{self, Vec};
164 use super::SpecExtend;
166 /// A priority queue implemented with a binary heap.
168 /// This will be a max-heap.
170 /// It is a logic error for an item to be modified in such a way that the
171 /// item's ordering relative to any other item, as determined by the `Ord`
172 /// trait, changes while it is in the heap. This is normally only possible
173 /// through `Cell`, `RefCell`, global state, I/O, or unsafe code.
178 /// use std::collections::BinaryHeap;
180 /// // Type inference lets us omit an explicit type signature (which
181 /// // would be `BinaryHeap<i32>` in this example).
182 /// let mut heap = BinaryHeap::new();
184 /// // We can use peek to look at the next item in the heap. In this case,
185 /// // there's no items in there yet so we get None.
186 /// assert_eq!(heap.peek(), None);
188 /// // Let's add some scores...
193 /// // Now peek shows the most important item in the heap.
194 /// assert_eq!(heap.peek(), Some(&5));
196 /// // We can check the length of a heap.
197 /// assert_eq!(heap.len(), 3);
199 /// // We can iterate over the items in the heap, although they are returned in
200 /// // a random order.
202 /// println!("{}", x);
205 /// // If we instead pop these scores, they should come back in order.
206 /// assert_eq!(heap.pop(), Some(5));
207 /// assert_eq!(heap.pop(), Some(2));
208 /// assert_eq!(heap.pop(), Some(1));
209 /// assert_eq!(heap.pop(), None);
211 /// // We can clear the heap of any remaining items.
214 /// // The heap should now be empty.
215 /// assert!(heap.is_empty())
217 #[stable(feature = "rust1", since = "1.0.0")]
218 pub struct BinaryHeap<T> {
222 /// A container object that represents the result of the [`peek_mut()`] method
223 /// on `BinaryHeap`. See its documentation for details.
225 /// [`peek_mut()`]: struct.BinaryHeap.html#method.peek_mut
226 #[stable(feature = "binary_heap_peek_mut", since = "1.12.0")]
227 pub struct PeekMut<'a, T: 'a + Ord> {
228 heap: &'a mut BinaryHeap<T>
231 #[stable(feature = "binary_heap_peek_mut", since = "1.12.0")]
232 impl<'a, T: Ord> Drop for PeekMut<'a, T> {
234 self.heap.sift_down(0);
238 #[stable(feature = "binary_heap_peek_mut", since = "1.12.0")]
239 impl<'a, T: Ord> Deref for PeekMut<'a, T> {
241 fn deref(&self) -> &T {
246 #[stable(feature = "binary_heap_peek_mut", since = "1.12.0")]
247 impl<'a, T: Ord> DerefMut for PeekMut<'a, T> {
248 fn deref_mut(&mut self) -> &mut T {
249 &mut self.heap.data[0]
253 #[stable(feature = "rust1", since = "1.0.0")]
254 impl<T: Clone> Clone for BinaryHeap<T> {
255 fn clone(&self) -> Self {
256 BinaryHeap { data: self.data.clone() }
259 fn clone_from(&mut self, source: &Self) {
260 self.data.clone_from(&source.data);
264 #[stable(feature = "rust1", since = "1.0.0")]
265 impl<T: Ord> Default for BinaryHeap<T> {
267 fn default() -> BinaryHeap<T> {
272 #[stable(feature = "binaryheap_debug", since = "1.4.0")]
273 impl<T: fmt::Debug + Ord> fmt::Debug for BinaryHeap<T> {
274 fn fmt(&self, f: &mut fmt::Formatter) -> fmt::Result {
275 f.debug_list().entries(self.iter()).finish()
279 impl<T: Ord> BinaryHeap<T> {
280 /// Creates an empty `BinaryHeap` as a max-heap.
287 /// use std::collections::BinaryHeap;
288 /// let mut heap = BinaryHeap::new();
291 #[stable(feature = "rust1", since = "1.0.0")]
292 pub fn new() -> BinaryHeap<T> {
293 BinaryHeap { data: vec![] }
296 /// Creates an empty `BinaryHeap` with a specific capacity.
297 /// This preallocates enough memory for `capacity` elements,
298 /// so that the `BinaryHeap` does not have to be reallocated
299 /// until it contains at least that many values.
306 /// use std::collections::BinaryHeap;
307 /// let mut heap = BinaryHeap::with_capacity(10);
310 #[stable(feature = "rust1", since = "1.0.0")]
311 pub fn with_capacity(capacity: usize) -> BinaryHeap<T> {
312 BinaryHeap { data: Vec::with_capacity(capacity) }
315 /// Returns an iterator visiting all values in the underlying vector, in
323 /// use std::collections::BinaryHeap;
324 /// let heap = BinaryHeap::from(vec![1, 2, 3, 4]);
326 /// // Print 1, 2, 3, 4 in arbitrary order
327 /// for x in heap.iter() {
328 /// println!("{}", x);
331 #[stable(feature = "rust1", since = "1.0.0")]
332 pub fn iter(&self) -> Iter<T> {
333 Iter { iter: self.data.iter() }
336 /// Returns the greatest item in the binary heap, or `None` if it is empty.
343 /// use std::collections::BinaryHeap;
344 /// let mut heap = BinaryHeap::new();
345 /// assert_eq!(heap.peek(), None);
350 /// assert_eq!(heap.peek(), Some(&5));
353 #[stable(feature = "rust1", since = "1.0.0")]
354 pub fn peek(&self) -> Option<&T> {
358 /// Returns a mutable reference to the greatest item in the binary heap, or
359 /// `None` if it is empty.
361 /// Note: If the `PeekMut` value is leaked, the heap may be in an
362 /// inconsistent state.
369 /// use std::collections::BinaryHeap;
370 /// let mut heap = BinaryHeap::new();
371 /// assert!(heap.peek_mut().is_none());
377 /// let mut val = heap.peek_mut().unwrap();
380 /// assert_eq!(heap.peek(), Some(&2));
382 #[stable(feature = "binary_heap_peek_mut", since = "1.12.0")]
383 pub fn peek_mut(&mut self) -> Option<PeekMut<T>> {
393 /// Returns the number of elements the binary heap can hold without reallocating.
400 /// use std::collections::BinaryHeap;
401 /// let mut heap = BinaryHeap::with_capacity(100);
402 /// assert!(heap.capacity() >= 100);
405 #[stable(feature = "rust1", since = "1.0.0")]
406 pub fn capacity(&self) -> usize {
410 /// Reserves the minimum capacity for exactly `additional` more elements to be inserted in the
411 /// given `BinaryHeap`. Does nothing if the capacity is already sufficient.
413 /// Note that the allocator may give the collection more space than it requests. Therefore
414 /// capacity can not be relied upon to be precisely minimal. Prefer `reserve` if future
415 /// insertions are expected.
419 /// Panics if the new capacity overflows `usize`.
426 /// use std::collections::BinaryHeap;
427 /// let mut heap = BinaryHeap::new();
428 /// heap.reserve_exact(100);
429 /// assert!(heap.capacity() >= 100);
432 #[stable(feature = "rust1", since = "1.0.0")]
433 pub fn reserve_exact(&mut self, additional: usize) {
434 self.data.reserve_exact(additional);
437 /// Reserves capacity for at least `additional` more elements to be inserted in the
438 /// `BinaryHeap`. The collection may reserve more space to avoid frequent reallocations.
442 /// Panics if the new capacity overflows `usize`.
449 /// use std::collections::BinaryHeap;
450 /// let mut heap = BinaryHeap::new();
451 /// heap.reserve(100);
452 /// assert!(heap.capacity() >= 100);
455 #[stable(feature = "rust1", since = "1.0.0")]
456 pub fn reserve(&mut self, additional: usize) {
457 self.data.reserve(additional);
460 /// Discards as much additional capacity as possible.
467 /// use std::collections::BinaryHeap;
468 /// let mut heap: BinaryHeap<i32> = BinaryHeap::with_capacity(100);
470 /// assert!(heap.capacity() >= 100);
471 /// heap.shrink_to_fit();
472 /// assert!(heap.capacity() == 0);
474 #[stable(feature = "rust1", since = "1.0.0")]
475 pub fn shrink_to_fit(&mut self) {
476 self.data.shrink_to_fit();
479 /// Removes the greatest item from the binary heap and returns it, or `None` if it
487 /// use std::collections::BinaryHeap;
488 /// let mut heap = BinaryHeap::from(vec![1, 3]);
490 /// assert_eq!(heap.pop(), Some(3));
491 /// assert_eq!(heap.pop(), Some(1));
492 /// assert_eq!(heap.pop(), None);
494 #[stable(feature = "rust1", since = "1.0.0")]
495 pub fn pop(&mut self) -> Option<T> {
496 self.data.pop().map(|mut item| {
497 if !self.is_empty() {
498 swap(&mut item, &mut self.data[0]);
499 self.sift_down_to_bottom(0);
505 /// Pushes an item onto the binary heap.
512 /// use std::collections::BinaryHeap;
513 /// let mut heap = BinaryHeap::new();
518 /// assert_eq!(heap.len(), 3);
519 /// assert_eq!(heap.peek(), Some(&5));
521 #[stable(feature = "rust1", since = "1.0.0")]
522 pub fn push(&mut self, item: T) {
523 let old_len = self.len();
524 self.data.push(item);
525 self.sift_up(0, old_len);
528 /// Pushes an item onto the binary heap, then pops the greatest item off the queue in
529 /// an optimized fashion.
536 /// #![feature(binary_heap_extras)]
538 /// use std::collections::BinaryHeap;
539 /// let mut heap = BinaryHeap::new();
543 /// assert_eq!(heap.push_pop(3), 5);
544 /// assert_eq!(heap.push_pop(9), 9);
545 /// assert_eq!(heap.len(), 2);
546 /// assert_eq!(heap.peek(), Some(&3));
548 #[unstable(feature = "binary_heap_extras",
549 reason = "needs to be audited",
551 pub fn push_pop(&mut self, mut item: T) -> T {
552 match self.data.get_mut(0) {
556 swap(&mut item, top);
567 /// Pops the greatest item off the binary heap, then pushes an item onto the queue in
568 /// an optimized fashion. The push is done regardless of whether the binary heap
576 /// #![feature(binary_heap_extras)]
578 /// use std::collections::BinaryHeap;
579 /// let mut heap = BinaryHeap::new();
581 /// assert_eq!(heap.replace(1), None);
582 /// assert_eq!(heap.replace(3), Some(1));
583 /// assert_eq!(heap.len(), 1);
584 /// assert_eq!(heap.peek(), Some(&3));
586 #[unstable(feature = "binary_heap_extras",
587 reason = "needs to be audited",
589 pub fn replace(&mut self, mut item: T) -> Option<T> {
590 if !self.is_empty() {
591 swap(&mut item, &mut self.data[0]);
600 /// Consumes the `BinaryHeap` and returns the underlying vector
601 /// in arbitrary order.
608 /// use std::collections::BinaryHeap;
609 /// let heap = BinaryHeap::from(vec![1, 2, 3, 4, 5, 6, 7]);
610 /// let vec = heap.into_vec();
612 /// // Will print in some order
614 /// println!("{}", x);
617 #[stable(feature = "binary_heap_extras_15", since = "1.5.0")]
618 pub fn into_vec(self) -> Vec<T> {
622 /// Consumes the `BinaryHeap` and returns a vector in sorted
623 /// (ascending) order.
630 /// use std::collections::BinaryHeap;
632 /// let mut heap = BinaryHeap::from(vec![1, 2, 4, 5, 7]);
636 /// let vec = heap.into_sorted_vec();
637 /// assert_eq!(vec, [1, 2, 3, 4, 5, 6, 7]);
639 #[stable(feature = "binary_heap_extras_15", since = "1.5.0")]
640 pub fn into_sorted_vec(mut self) -> Vec<T> {
641 let mut end = self.len();
644 self.data.swap(0, end);
645 self.sift_down_range(0, end);
650 // The implementations of sift_up and sift_down use unsafe blocks in
651 // order to move an element out of the vector (leaving behind a
652 // hole), shift along the others and move the removed element back into the
653 // vector at the final location of the hole.
654 // The `Hole` type is used to represent this, and make sure
655 // the hole is filled back at the end of its scope, even on panic.
656 // Using a hole reduces the constant factor compared to using swaps,
657 // which involves twice as many moves.
658 fn sift_up(&mut self, start: usize, pos: usize) {
660 // Take out the value at `pos` and create a hole.
661 let mut hole = Hole::new(&mut self.data, pos);
663 while hole.pos() > start {
664 let parent = (hole.pos() - 1) / 2;
665 if hole.element() <= hole.get(parent) {
668 hole.move_to(parent);
673 /// Take an element at `pos` and move it down the heap,
674 /// while its children are larger.
675 fn sift_down_range(&mut self, pos: usize, end: usize) {
677 let mut hole = Hole::new(&mut self.data, pos);
678 let mut child = 2 * pos + 1;
680 let right = child + 1;
681 // compare with the greater of the two children
682 if right < end && !(hole.get(child) > hole.get(right)) {
685 // if we are already in order, stop.
686 if hole.element() >= hole.get(child) {
690 child = 2 * hole.pos() + 1;
695 fn sift_down(&mut self, pos: usize) {
696 let len = self.len();
697 self.sift_down_range(pos, len);
700 /// Take an element at `pos` and move it all the way down the heap,
701 /// then sift it up to its position.
703 /// Note: This is faster when the element is known to be large / should
704 /// be closer to the bottom.
705 fn sift_down_to_bottom(&mut self, mut pos: usize) {
706 let end = self.len();
709 let mut hole = Hole::new(&mut self.data, pos);
710 let mut child = 2 * pos + 1;
712 let right = child + 1;
713 // compare with the greater of the two children
714 if right < end && !(hole.get(child) > hole.get(right)) {
718 child = 2 * hole.pos() + 1;
722 self.sift_up(start, pos);
725 /// Returns the length of the binary heap.
732 /// use std::collections::BinaryHeap;
733 /// let heap = BinaryHeap::from(vec![1, 3]);
735 /// assert_eq!(heap.len(), 2);
737 #[stable(feature = "rust1", since = "1.0.0")]
738 pub fn len(&self) -> usize {
742 /// Checks if the binary heap is empty.
749 /// use std::collections::BinaryHeap;
750 /// let mut heap = BinaryHeap::new();
752 /// assert!(heap.is_empty());
758 /// assert!(!heap.is_empty());
760 #[stable(feature = "rust1", since = "1.0.0")]
761 pub fn is_empty(&self) -> bool {
765 /// Clears the binary heap, returning an iterator over the removed elements.
767 /// The elements are removed in arbitrary order.
774 /// use std::collections::BinaryHeap;
775 /// let mut heap = BinaryHeap::from(vec![1, 3]);
777 /// assert!(!heap.is_empty());
779 /// for x in heap.drain() {
780 /// println!("{}", x);
783 /// assert!(heap.is_empty());
786 #[stable(feature = "drain", since = "1.6.0")]
787 pub fn drain(&mut self) -> Drain<T> {
788 Drain { iter: self.data.drain(..) }
791 /// Drops all items from the binary heap.
798 /// use std::collections::BinaryHeap;
799 /// let mut heap = BinaryHeap::from(vec![1, 3]);
801 /// assert!(!heap.is_empty());
805 /// assert!(heap.is_empty());
807 #[stable(feature = "rust1", since = "1.0.0")]
808 pub fn clear(&mut self) {
812 fn rebuild(&mut self) {
813 let mut n = self.len() / 2;
820 /// Moves all the elements of `other` into `self`, leaving `other` empty.
827 /// use std::collections::BinaryHeap;
829 /// let v = vec![-10, 1, 2, 3, 3];
830 /// let mut a = BinaryHeap::from(v);
832 /// let v = vec![-20, 5, 43];
833 /// let mut b = BinaryHeap::from(v);
835 /// a.append(&mut b);
837 /// assert_eq!(a.into_sorted_vec(), [-20, -10, 1, 2, 3, 3, 5, 43]);
838 /// assert!(b.is_empty());
840 #[stable(feature = "binary_heap_append", since = "1.11.0")]
841 pub fn append(&mut self, other: &mut Self) {
842 if self.len() < other.len() {
846 if other.is_empty() {
851 fn log2_fast(x: usize) -> usize {
852 8 * size_of::<usize>() - (x.leading_zeros() as usize) - 1
855 // `rebuild` takes O(len1 + len2) operations
856 // and about 2 * (len1 + len2) comparisons in the worst case
857 // while `extend` takes O(len2 * log_2(len1)) operations
858 // and about 1 * len2 * log_2(len1) comparisons in the worst case,
859 // assuming len1 >= len2.
861 fn better_to_rebuild(len1: usize, len2: usize) -> bool {
862 2 * (len1 + len2) < len2 * log2_fast(len1)
865 if better_to_rebuild(self.len(), other.len()) {
866 self.data.append(&mut other.data);
869 self.extend(other.drain());
874 /// Hole represents a hole in a slice i.e. an index without valid value
875 /// (because it was moved from or duplicated).
876 /// In drop, `Hole` will restore the slice by filling the hole
877 /// position with the value that was originally removed.
878 struct Hole<'a, T: 'a> {
880 /// `elt` is always `Some` from new until drop.
885 impl<'a, T> Hole<'a, T> {
886 /// Create a new Hole at index `pos`.
887 fn new(data: &'a mut [T], pos: usize) -> Self {
889 let elt = ptr::read(&data[pos]);
899 fn pos(&self) -> usize {
903 /// Return a reference to the element removed
905 fn element(&self) -> &T {
906 self.elt.as_ref().unwrap()
909 /// Return a reference to the element at `index`.
911 /// Panics if the index is out of bounds.
913 /// Unsafe because index must not equal pos.
915 unsafe fn get(&self, index: usize) -> &T {
916 debug_assert!(index != self.pos);
920 /// Move hole to new location
922 /// Unsafe because index must not equal pos.
924 unsafe fn move_to(&mut self, index: usize) {
925 debug_assert!(index != self.pos);
926 let index_ptr: *const _ = &self.data[index];
927 let hole_ptr = &mut self.data[self.pos];
928 ptr::copy_nonoverlapping(index_ptr, hole_ptr, 1);
933 impl<'a, T> Drop for Hole<'a, T> {
935 // fill the hole again
938 ptr::write(&mut self.data[pos], self.elt.take().unwrap());
943 /// `BinaryHeap` iterator.
944 #[stable(feature = "rust1", since = "1.0.0")]
945 pub struct Iter<'a, T: 'a> {
946 iter: slice::Iter<'a, T>,
949 // FIXME(#19839) Remove in favor of `#[derive(Clone)]`
950 #[stable(feature = "rust1", since = "1.0.0")]
951 impl<'a, T> Clone for Iter<'a, T> {
952 fn clone(&self) -> Iter<'a, T> {
953 Iter { iter: self.iter.clone() }
957 #[stable(feature = "rust1", since = "1.0.0")]
958 impl<'a, T> Iterator for Iter<'a, T> {
962 fn next(&mut self) -> Option<&'a T> {
967 fn size_hint(&self) -> (usize, Option<usize>) {
968 self.iter.size_hint()
972 #[stable(feature = "rust1", since = "1.0.0")]
973 impl<'a, T> DoubleEndedIterator for Iter<'a, T> {
975 fn next_back(&mut self) -> Option<&'a T> {
976 self.iter.next_back()
980 #[stable(feature = "rust1", since = "1.0.0")]
981 impl<'a, T> ExactSizeIterator for Iter<'a, T> {}
983 #[unstable(feature = "fused", issue = "35602")]
984 impl<'a, T> FusedIterator for Iter<'a, T> {}
986 /// An iterator that moves out of a `BinaryHeap`.
987 #[stable(feature = "rust1", since = "1.0.0")]
989 pub struct IntoIter<T> {
990 iter: vec::IntoIter<T>,
993 #[stable(feature = "rust1", since = "1.0.0")]
994 impl<T> Iterator for IntoIter<T> {
998 fn next(&mut self) -> Option<T> {
1003 fn size_hint(&self) -> (usize, Option<usize>) {
1004 self.iter.size_hint()
1008 #[stable(feature = "rust1", since = "1.0.0")]
1009 impl<T> DoubleEndedIterator for IntoIter<T> {
1011 fn next_back(&mut self) -> Option<T> {
1012 self.iter.next_back()
1016 #[stable(feature = "rust1", since = "1.0.0")]
1017 impl<T> ExactSizeIterator for IntoIter<T> {}
1019 #[unstable(feature = "fused", issue = "35602")]
1020 impl<T> FusedIterator for IntoIter<T> {}
1022 /// An iterator that drains a `BinaryHeap`.
1023 #[stable(feature = "drain", since = "1.6.0")]
1024 pub struct Drain<'a, T: 'a> {
1025 iter: vec::Drain<'a, T>,
1028 #[stable(feature = "rust1", since = "1.0.0")]
1029 impl<'a, T: 'a> Iterator for Drain<'a, T> {
1033 fn next(&mut self) -> Option<T> {
1038 fn size_hint(&self) -> (usize, Option<usize>) {
1039 self.iter.size_hint()
1043 #[stable(feature = "rust1", since = "1.0.0")]
1044 impl<'a, T: 'a> DoubleEndedIterator for Drain<'a, T> {
1046 fn next_back(&mut self) -> Option<T> {
1047 self.iter.next_back()
1051 #[stable(feature = "rust1", since = "1.0.0")]
1052 impl<'a, T: 'a> ExactSizeIterator for Drain<'a, T> {}
1054 #[unstable(feature = "fused", issue = "35602")]
1055 impl<'a, T: 'a> FusedIterator for Drain<'a, T> {}
1057 #[stable(feature = "rust1", since = "1.0.0")]
1058 impl<T: Ord> From<Vec<T>> for BinaryHeap<T> {
1059 fn from(vec: Vec<T>) -> BinaryHeap<T> {
1060 let mut heap = BinaryHeap { data: vec };
1066 #[stable(feature = "rust1", since = "1.0.0")]
1067 impl<T> From<BinaryHeap<T>> for Vec<T> {
1068 fn from(heap: BinaryHeap<T>) -> Vec<T> {
1073 #[stable(feature = "rust1", since = "1.0.0")]
1074 impl<T: Ord> FromIterator<T> for BinaryHeap<T> {
1075 fn from_iter<I: IntoIterator<Item = T>>(iter: I) -> BinaryHeap<T> {
1076 BinaryHeap::from(iter.into_iter().collect::<Vec<_>>())
1080 #[stable(feature = "rust1", since = "1.0.0")]
1081 impl<T: Ord> IntoIterator for BinaryHeap<T> {
1083 type IntoIter = IntoIter<T>;
1085 /// Creates a consuming iterator, that is, one that moves each value out of
1086 /// the binary heap in arbitrary order. The binary heap cannot be used
1087 /// after calling this.
1094 /// use std::collections::BinaryHeap;
1095 /// let heap = BinaryHeap::from(vec![1, 2, 3, 4]);
1097 /// // Print 1, 2, 3, 4 in arbitrary order
1098 /// for x in heap.into_iter() {
1099 /// // x has type i32, not &i32
1100 /// println!("{}", x);
1103 fn into_iter(self) -> IntoIter<T> {
1104 IntoIter { iter: self.data.into_iter() }
1108 #[stable(feature = "rust1", since = "1.0.0")]
1109 impl<'a, T> IntoIterator for &'a BinaryHeap<T> where T: Ord {
1111 type IntoIter = Iter<'a, T>;
1113 fn into_iter(self) -> Iter<'a, T> {
1118 #[stable(feature = "rust1", since = "1.0.0")]
1119 impl<T: Ord> Extend<T> for BinaryHeap<T> {
1121 fn extend<I: IntoIterator<Item = T>>(&mut self, iter: I) {
1122 <Self as SpecExtend<I>>::spec_extend(self, iter);
1126 impl<T: Ord, I: IntoIterator<Item = T>> SpecExtend<I> for BinaryHeap<T> {
1127 default fn spec_extend(&mut self, iter: I) {
1128 self.extend_desugared(iter.into_iter());
1132 impl<T: Ord> SpecExtend<BinaryHeap<T>> for BinaryHeap<T> {
1133 fn spec_extend(&mut self, ref mut other: BinaryHeap<T>) {
1138 impl<T: Ord> BinaryHeap<T> {
1139 fn extend_desugared<I: IntoIterator<Item = T>>(&mut self, iter: I) {
1140 let iterator = iter.into_iter();
1141 let (lower, _) = iterator.size_hint();
1143 self.reserve(lower);
1145 for elem in iterator {
1151 #[stable(feature = "extend_ref", since = "1.2.0")]
1152 impl<'a, T: 'a + Ord + Copy> Extend<&'a T> for BinaryHeap<T> {
1153 fn extend<I: IntoIterator<Item = &'a T>>(&mut self, iter: I) {
1154 self.extend(iter.into_iter().cloned());