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;
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 #[unstable(feature = "binary_heap_peek_mut", issue = "34392")]
227 pub struct PeekMut<'a, T: 'a + Ord> {
228 heap: &'a mut BinaryHeap<T>
231 #[unstable(feature = "binary_heap_peek_mut", issue = "34392")]
232 impl<'a, T: Ord> Drop for PeekMut<'a, T> {
234 self.heap.sift_down(0);
238 #[unstable(feature = "binary_heap_peek_mut", issue = "34392")]
239 impl<'a, T: Ord> Deref for PeekMut<'a, T> {
241 fn deref(&self) -> &T {
246 #[unstable(feature = "binary_heap_peek_mut", issue = "34392")]
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 /// #![feature(binary_heap_peek_mut)]
370 /// use std::collections::BinaryHeap;
371 /// let mut heap = BinaryHeap::new();
372 /// assert!(heap.peek_mut().is_none());
378 /// let mut val = heap.peek_mut().unwrap();
381 /// assert_eq!(heap.peek(), Some(&2));
383 #[unstable(feature = "binary_heap_peek_mut", issue = "34392")]
384 pub fn peek_mut(&mut self) -> Option<PeekMut<T>> {
394 /// Returns the number of elements the binary heap can hold without reallocating.
401 /// use std::collections::BinaryHeap;
402 /// let mut heap = BinaryHeap::with_capacity(100);
403 /// assert!(heap.capacity() >= 100);
406 #[stable(feature = "rust1", since = "1.0.0")]
407 pub fn capacity(&self) -> usize {
411 /// Reserves the minimum capacity for exactly `additional` more elements to be inserted in the
412 /// given `BinaryHeap`. Does nothing if the capacity is already sufficient.
414 /// Note that the allocator may give the collection more space than it requests. Therefore
415 /// capacity can not be relied upon to be precisely minimal. Prefer `reserve` if future
416 /// insertions are expected.
420 /// Panics if the new capacity overflows `usize`.
427 /// use std::collections::BinaryHeap;
428 /// let mut heap = BinaryHeap::new();
429 /// heap.reserve_exact(100);
430 /// assert!(heap.capacity() >= 100);
433 #[stable(feature = "rust1", since = "1.0.0")]
434 pub fn reserve_exact(&mut self, additional: usize) {
435 self.data.reserve_exact(additional);
438 /// Reserves capacity for at least `additional` more elements to be inserted in the
439 /// `BinaryHeap`. The collection may reserve more space to avoid frequent reallocations.
443 /// Panics if the new capacity overflows `usize`.
450 /// use std::collections::BinaryHeap;
451 /// let mut heap = BinaryHeap::new();
452 /// heap.reserve(100);
453 /// assert!(heap.capacity() >= 100);
456 #[stable(feature = "rust1", since = "1.0.0")]
457 pub fn reserve(&mut self, additional: usize) {
458 self.data.reserve(additional);
461 /// Discards as much additional capacity as possible.
468 /// use std::collections::BinaryHeap;
469 /// let mut heap: BinaryHeap<i32> = BinaryHeap::with_capacity(100);
471 /// assert!(heap.capacity() >= 100);
472 /// heap.shrink_to_fit();
473 /// assert!(heap.capacity() == 0);
475 #[stable(feature = "rust1", since = "1.0.0")]
476 pub fn shrink_to_fit(&mut self) {
477 self.data.shrink_to_fit();
480 /// Removes the greatest item from the binary heap and returns it, or `None` if it
488 /// use std::collections::BinaryHeap;
489 /// let mut heap = BinaryHeap::from(vec![1, 3]);
491 /// assert_eq!(heap.pop(), Some(3));
492 /// assert_eq!(heap.pop(), Some(1));
493 /// assert_eq!(heap.pop(), None);
495 #[stable(feature = "rust1", since = "1.0.0")]
496 pub fn pop(&mut self) -> Option<T> {
497 self.data.pop().map(|mut item| {
498 if !self.is_empty() {
499 swap(&mut item, &mut self.data[0]);
500 self.sift_down_to_bottom(0);
506 /// Pushes an item onto the binary heap.
513 /// use std::collections::BinaryHeap;
514 /// let mut heap = BinaryHeap::new();
519 /// assert_eq!(heap.len(), 3);
520 /// assert_eq!(heap.peek(), Some(&5));
522 #[stable(feature = "rust1", since = "1.0.0")]
523 pub fn push(&mut self, item: T) {
524 let old_len = self.len();
525 self.data.push(item);
526 self.sift_up(0, old_len);
529 /// Pushes an item onto the binary heap, then pops the greatest item off the queue in
530 /// an optimized fashion.
537 /// #![feature(binary_heap_extras)]
539 /// use std::collections::BinaryHeap;
540 /// let mut heap = BinaryHeap::new();
544 /// assert_eq!(heap.push_pop(3), 5);
545 /// assert_eq!(heap.push_pop(9), 9);
546 /// assert_eq!(heap.len(), 2);
547 /// assert_eq!(heap.peek(), Some(&3));
549 #[unstable(feature = "binary_heap_extras",
550 reason = "needs to be audited",
552 pub fn push_pop(&mut self, mut item: T) -> T {
553 match self.data.get_mut(0) {
557 swap(&mut item, top);
568 /// Pops the greatest item off the binary heap, then pushes an item onto the queue in
569 /// an optimized fashion. The push is done regardless of whether the binary heap
577 /// #![feature(binary_heap_extras)]
579 /// use std::collections::BinaryHeap;
580 /// let mut heap = BinaryHeap::new();
582 /// assert_eq!(heap.replace(1), None);
583 /// assert_eq!(heap.replace(3), Some(1));
584 /// assert_eq!(heap.len(), 1);
585 /// assert_eq!(heap.peek(), Some(&3));
587 #[unstable(feature = "binary_heap_extras",
588 reason = "needs to be audited",
590 pub fn replace(&mut self, mut item: T) -> Option<T> {
591 if !self.is_empty() {
592 swap(&mut item, &mut self.data[0]);
601 /// Consumes the `BinaryHeap` and returns the underlying vector
602 /// in arbitrary order.
609 /// use std::collections::BinaryHeap;
610 /// let heap = BinaryHeap::from(vec![1, 2, 3, 4, 5, 6, 7]);
611 /// let vec = heap.into_vec();
613 /// // Will print in some order
615 /// println!("{}", x);
618 #[stable(feature = "binary_heap_extras_15", since = "1.5.0")]
619 pub fn into_vec(self) -> Vec<T> {
623 /// Consumes the `BinaryHeap` and returns a vector in sorted
624 /// (ascending) order.
631 /// use std::collections::BinaryHeap;
633 /// let mut heap = BinaryHeap::from(vec![1, 2, 4, 5, 7]);
637 /// let vec = heap.into_sorted_vec();
638 /// assert_eq!(vec, [1, 2, 3, 4, 5, 6, 7]);
640 #[stable(feature = "binary_heap_extras_15", since = "1.5.0")]
641 pub fn into_sorted_vec(mut self) -> Vec<T> {
642 let mut end = self.len();
645 self.data.swap(0, end);
646 self.sift_down_range(0, end);
651 // The implementations of sift_up and sift_down use unsafe blocks in
652 // order to move an element out of the vector (leaving behind a
653 // hole), shift along the others and move the removed element back into the
654 // vector at the final location of the hole.
655 // The `Hole` type is used to represent this, and make sure
656 // the hole is filled back at the end of its scope, even on panic.
657 // Using a hole reduces the constant factor compared to using swaps,
658 // which involves twice as many moves.
659 fn sift_up(&mut self, start: usize, pos: usize) {
661 // Take out the value at `pos` and create a hole.
662 let mut hole = Hole::new(&mut self.data, pos);
664 while hole.pos() > start {
665 let parent = (hole.pos() - 1) / 2;
666 if hole.element() <= hole.get(parent) {
669 hole.move_to(parent);
674 /// Take an element at `pos` and move it down the heap,
675 /// while its children are larger.
676 fn sift_down_range(&mut self, pos: usize, end: usize) {
678 let mut hole = Hole::new(&mut self.data, pos);
679 let mut child = 2 * pos + 1;
681 let right = child + 1;
682 // compare with the greater of the two children
683 if right < end && !(hole.get(child) > hole.get(right)) {
686 // if we are already in order, stop.
687 if hole.element() >= hole.get(child) {
691 child = 2 * hole.pos() + 1;
696 fn sift_down(&mut self, pos: usize) {
697 let len = self.len();
698 self.sift_down_range(pos, len);
701 /// Take an element at `pos` and move it all the way down the heap,
702 /// then sift it up to its position.
704 /// Note: This is faster when the element is known to be large / should
705 /// be closer to the bottom.
706 fn sift_down_to_bottom(&mut self, mut pos: usize) {
707 let end = self.len();
710 let mut hole = Hole::new(&mut self.data, pos);
711 let mut child = 2 * pos + 1;
713 let right = child + 1;
714 // compare with the greater of the two children
715 if right < end && !(hole.get(child) > hole.get(right)) {
719 child = 2 * hole.pos() + 1;
723 self.sift_up(start, pos);
726 /// Returns the length of the binary heap.
733 /// use std::collections::BinaryHeap;
734 /// let heap = BinaryHeap::from(vec![1, 3]);
736 /// assert_eq!(heap.len(), 2);
738 #[stable(feature = "rust1", since = "1.0.0")]
739 pub fn len(&self) -> usize {
743 /// Checks if the binary heap is empty.
750 /// use std::collections::BinaryHeap;
751 /// let mut heap = BinaryHeap::new();
753 /// assert!(heap.is_empty());
759 /// assert!(!heap.is_empty());
761 #[stable(feature = "rust1", since = "1.0.0")]
762 pub fn is_empty(&self) -> bool {
766 /// Clears the binary heap, returning an iterator over the removed elements.
768 /// The elements are removed in arbitrary order.
775 /// use std::collections::BinaryHeap;
776 /// let mut heap = BinaryHeap::from(vec![1, 3]);
778 /// assert!(!heap.is_empty());
780 /// for x in heap.drain() {
781 /// println!("{}", x);
784 /// assert!(heap.is_empty());
787 #[stable(feature = "drain", since = "1.6.0")]
788 pub fn drain(&mut self) -> Drain<T> {
789 Drain { iter: self.data.drain(..) }
792 /// Drops all items from the binary heap.
799 /// use std::collections::BinaryHeap;
800 /// let mut heap = BinaryHeap::from(vec![1, 3]);
802 /// assert!(!heap.is_empty());
806 /// assert!(heap.is_empty());
808 #[stable(feature = "rust1", since = "1.0.0")]
809 pub fn clear(&mut self) {
813 fn rebuild(&mut self) {
814 let mut n = self.len() / 2;
821 /// Moves all the elements of `other` into `self`, leaving `other` empty.
828 /// use std::collections::BinaryHeap;
830 /// let v = vec![-10, 1, 2, 3, 3];
831 /// let mut a = BinaryHeap::from(v);
833 /// let v = vec![-20, 5, 43];
834 /// let mut b = BinaryHeap::from(v);
836 /// a.append(&mut b);
838 /// assert_eq!(a.into_sorted_vec(), [-20, -10, 1, 2, 3, 3, 5, 43]);
839 /// assert!(b.is_empty());
841 #[stable(feature = "binary_heap_append", since = "1.11.0")]
842 pub fn append(&mut self, other: &mut Self) {
843 if self.len() < other.len() {
847 if other.is_empty() {
852 fn log2_fast(x: usize) -> usize {
853 8 * size_of::<usize>() - (x.leading_zeros() as usize) - 1
856 // `rebuild` takes O(len1 + len2) operations
857 // and about 2 * (len1 + len2) comparisons in the worst case
858 // while `extend` takes O(len2 * log_2(len1)) operations
859 // and about 1 * len2 * log_2(len1) comparisons in the worst case,
860 // assuming len1 >= len2.
862 fn better_to_rebuild(len1: usize, len2: usize) -> bool {
863 2 * (len1 + len2) < len2 * log2_fast(len1)
866 if better_to_rebuild(self.len(), other.len()) {
867 self.data.append(&mut other.data);
870 self.extend(other.drain());
875 /// Hole represents a hole in a slice i.e. an index without valid value
876 /// (because it was moved from or duplicated).
877 /// In drop, `Hole` will restore the slice by filling the hole
878 /// position with the value that was originally removed.
879 struct Hole<'a, T: 'a> {
881 /// `elt` is always `Some` from new until drop.
886 impl<'a, T> Hole<'a, T> {
887 /// Create a new Hole at index `pos`.
888 fn new(data: &'a mut [T], pos: usize) -> Self {
890 let elt = ptr::read(&data[pos]);
900 fn pos(&self) -> usize {
904 /// Return a reference to the element removed
906 fn element(&self) -> &T {
907 self.elt.as_ref().unwrap()
910 /// Return a reference to the element at `index`.
912 /// Panics if the index is out of bounds.
914 /// Unsafe because index must not equal pos.
916 unsafe fn get(&self, index: usize) -> &T {
917 debug_assert!(index != self.pos);
921 /// Move hole to new location
923 /// Unsafe because index must not equal pos.
925 unsafe fn move_to(&mut self, index: usize) {
926 debug_assert!(index != self.pos);
927 let index_ptr: *const _ = &self.data[index];
928 let hole_ptr = &mut self.data[self.pos];
929 ptr::copy_nonoverlapping(index_ptr, hole_ptr, 1);
934 impl<'a, T> Drop for Hole<'a, T> {
936 // fill the hole again
939 ptr::write(&mut self.data[pos], self.elt.take().unwrap());
944 /// `BinaryHeap` iterator.
945 #[stable(feature = "rust1", since = "1.0.0")]
946 pub struct Iter<'a, T: 'a> {
947 iter: slice::Iter<'a, T>,
950 // FIXME(#19839) Remove in favor of `#[derive(Clone)]`
951 #[stable(feature = "rust1", since = "1.0.0")]
952 impl<'a, T> Clone for Iter<'a, T> {
953 fn clone(&self) -> Iter<'a, T> {
954 Iter { iter: self.iter.clone() }
958 #[stable(feature = "rust1", since = "1.0.0")]
959 impl<'a, T> Iterator for Iter<'a, T> {
963 fn next(&mut self) -> Option<&'a T> {
968 fn size_hint(&self) -> (usize, Option<usize>) {
969 self.iter.size_hint()
973 #[stable(feature = "rust1", since = "1.0.0")]
974 impl<'a, T> DoubleEndedIterator for Iter<'a, T> {
976 fn next_back(&mut self) -> Option<&'a T> {
977 self.iter.next_back()
981 #[stable(feature = "rust1", since = "1.0.0")]
982 impl<'a, T> ExactSizeIterator for Iter<'a, T> {}
984 /// An iterator that moves out of a `BinaryHeap`.
985 #[stable(feature = "rust1", since = "1.0.0")]
987 pub struct IntoIter<T> {
988 iter: vec::IntoIter<T>,
991 #[stable(feature = "rust1", since = "1.0.0")]
992 impl<T> Iterator for IntoIter<T> {
996 fn next(&mut self) -> Option<T> {
1001 fn size_hint(&self) -> (usize, Option<usize>) {
1002 self.iter.size_hint()
1006 #[stable(feature = "rust1", since = "1.0.0")]
1007 impl<T> DoubleEndedIterator for IntoIter<T> {
1009 fn next_back(&mut self) -> Option<T> {
1010 self.iter.next_back()
1014 #[stable(feature = "rust1", since = "1.0.0")]
1015 impl<T> ExactSizeIterator for IntoIter<T> {}
1017 /// An iterator that drains a `BinaryHeap`.
1018 #[stable(feature = "drain", since = "1.6.0")]
1019 pub struct Drain<'a, T: 'a> {
1020 iter: vec::Drain<'a, T>,
1023 #[stable(feature = "rust1", since = "1.0.0")]
1024 impl<'a, T: 'a> Iterator for Drain<'a, T> {
1028 fn next(&mut self) -> Option<T> {
1033 fn size_hint(&self) -> (usize, Option<usize>) {
1034 self.iter.size_hint()
1038 #[stable(feature = "rust1", since = "1.0.0")]
1039 impl<'a, T: 'a> DoubleEndedIterator for Drain<'a, T> {
1041 fn next_back(&mut self) -> Option<T> {
1042 self.iter.next_back()
1046 #[stable(feature = "rust1", since = "1.0.0")]
1047 impl<'a, T: 'a> ExactSizeIterator for Drain<'a, T> {}
1049 #[stable(feature = "rust1", since = "1.0.0")]
1050 impl<T: Ord> From<Vec<T>> for BinaryHeap<T> {
1051 fn from(vec: Vec<T>) -> BinaryHeap<T> {
1052 let mut heap = BinaryHeap { data: vec };
1058 #[stable(feature = "rust1", since = "1.0.0")]
1059 impl<T> From<BinaryHeap<T>> for Vec<T> {
1060 fn from(heap: BinaryHeap<T>) -> Vec<T> {
1065 #[stable(feature = "rust1", since = "1.0.0")]
1066 impl<T: Ord> FromIterator<T> for BinaryHeap<T> {
1067 fn from_iter<I: IntoIterator<Item = T>>(iter: I) -> BinaryHeap<T> {
1068 BinaryHeap::from(iter.into_iter().collect::<Vec<_>>())
1072 #[stable(feature = "rust1", since = "1.0.0")]
1073 impl<T: Ord> IntoIterator for BinaryHeap<T> {
1075 type IntoIter = IntoIter<T>;
1077 /// Creates a consuming iterator, that is, one that moves each value out of
1078 /// the binary heap in arbitrary order. The binary heap cannot be used
1079 /// after calling this.
1086 /// use std::collections::BinaryHeap;
1087 /// let heap = BinaryHeap::from(vec![1, 2, 3, 4]);
1089 /// // Print 1, 2, 3, 4 in arbitrary order
1090 /// for x in heap.into_iter() {
1091 /// // x has type i32, not &i32
1092 /// println!("{}", x);
1095 fn into_iter(self) -> IntoIter<T> {
1096 IntoIter { iter: self.data.into_iter() }
1100 #[stable(feature = "rust1", since = "1.0.0")]
1101 impl<'a, T> IntoIterator for &'a BinaryHeap<T> where T: Ord {
1103 type IntoIter = Iter<'a, T>;
1105 fn into_iter(self) -> Iter<'a, T> {
1110 #[stable(feature = "rust1", since = "1.0.0")]
1111 impl<T: Ord> Extend<T> for BinaryHeap<T> {
1113 fn extend<I: IntoIterator<Item = T>>(&mut self, iter: I) {
1114 <Self as SpecExtend<I>>::spec_extend(self, iter);
1118 impl<T: Ord, I: IntoIterator<Item = T>> SpecExtend<I> for BinaryHeap<T> {
1119 default fn spec_extend(&mut self, iter: I) {
1120 self.extend_desugared(iter.into_iter());
1124 impl<T: Ord> SpecExtend<BinaryHeap<T>> for BinaryHeap<T> {
1125 fn spec_extend(&mut self, ref mut other: BinaryHeap<T>) {
1130 impl<T: Ord> BinaryHeap<T> {
1131 fn extend_desugared<I: IntoIterator<Item = T>>(&mut self, iter: I) {
1132 let iterator = iter.into_iter();
1133 let (lower, _) = iterator.size_hint();
1135 self.reserve(lower);
1137 for elem in iterator {
1143 #[stable(feature = "extend_ref", since = "1.2.0")]
1144 impl<'a, T: 'a + Ord + Copy> Extend<&'a T> for BinaryHeap<T> {
1145 fn extend<I: IntoIterator<Item = &'a T>>(&mut self, iter: I) {
1146 self.extend(iter.into_iter().cloned());