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
28 //! [`BinaryHeap`]: struct.BinaryHeap.html
31 //! use std::cmp::Ordering;
32 //! use std::collections::BinaryHeap;
35 //! #[derive(Copy, Clone, Eq, PartialEq)]
41 //! // The priority queue depends on `Ord`.
42 //! // Explicitly implement the trait so the queue becomes a min-heap
43 //! // instead of a max-heap.
44 //! impl Ord for State {
45 //! fn cmp(&self, other: &State) -> Ordering {
46 //! // Notice that the we flip the ordering on costs.
47 //! // In case of a tie we compare positions - this step is necessary
48 //! // to make implementations of `PartialEq` and `Ord` consistent.
49 //! other.cost.cmp(&self.cost)
50 //! .then_with(|| self.position.cmp(&other.position))
54 //! // `PartialOrd` needs to be implemented as well.
55 //! impl PartialOrd for State {
56 //! fn partial_cmp(&self, other: &State) -> Option<Ordering> {
57 //! Some(self.cmp(other))
61 //! // Each node is represented as an `usize`, for a shorter implementation.
67 //! // Dijkstra's shortest path algorithm.
69 //! // Start at `start` and use `dist` to track the current shortest distance
70 //! // to each node. This implementation isn't memory-efficient as it may leave duplicate
71 //! // nodes in the queue. It also uses `usize::MAX` as a sentinel value,
72 //! // for a simpler implementation.
73 //! fn shortest_path(adj_list: &Vec<Vec<Edge>>, start: usize, goal: usize) -> Option<usize> {
74 //! // dist[node] = current shortest distance from `start` to `node`
75 //! let mut dist: Vec<_> = (0..adj_list.len()).map(|_| usize::MAX).collect();
77 //! let mut heap = BinaryHeap::new();
79 //! // We're at `start`, with a zero cost
81 //! heap.push(State { cost: 0, position: start });
83 //! // Examine the frontier with lower cost nodes first (min-heap)
84 //! while let Some(State { cost, position }) = heap.pop() {
85 //! // Alternatively we could have continued to find all shortest paths
86 //! if position == goal { return Some(cost); }
88 //! // Important as we may have already found a better way
89 //! if cost > dist[position] { continue; }
91 //! // For each node we can reach, see if we can find a way with
92 //! // a lower cost going through this node
93 //! for edge in &adj_list[position] {
94 //! let next = State { cost: cost + edge.cost, position: edge.node };
96 //! // If so, add it to the frontier and continue
97 //! if next.cost < dist[next.position] {
99 //! // Relaxation, we have now found a better way
100 //! dist[next.position] = next.cost;
105 //! // Goal not reachable
110 //! // This is the directed graph we're going to use.
111 //! // The node numbers correspond to the different states,
112 //! // and the edge weights symbolize the cost of moving
113 //! // from one node to another.
114 //! // Note that the edges are one-way.
117 //! // +-----------------+
120 //! // 0 -----> 1 -----> 3 ---> 4
124 //! // +------> 2 -------+ |
126 //! // +---------------+
128 //! // The graph is represented as an adjacency list where each index,
129 //! // corresponding to a node value, has a list of outgoing edges.
130 //! // Chosen for its efficiency.
131 //! let graph = vec![
133 //! vec![Edge { node: 2, cost: 10 },
134 //! Edge { node: 1, cost: 1 }],
136 //! vec![Edge { node: 3, cost: 2 }],
138 //! vec![Edge { node: 1, cost: 1 },
139 //! Edge { node: 3, cost: 3 },
140 //! Edge { node: 4, cost: 1 }],
142 //! vec![Edge { node: 0, cost: 7 },
143 //! Edge { node: 4, cost: 2 }],
147 //! assert_eq!(shortest_path(&graph, 0, 1), Some(1));
148 //! assert_eq!(shortest_path(&graph, 0, 3), Some(3));
149 //! assert_eq!(shortest_path(&graph, 3, 0), Some(7));
150 //! assert_eq!(shortest_path(&graph, 0, 4), Some(5));
151 //! assert_eq!(shortest_path(&graph, 4, 0), None);
155 #![allow(missing_docs)]
156 #![stable(feature = "rust1", since = "1.0.0")]
158 use core::ops::{Deref, DerefMut};
159 use core::iter::{FromIterator, FusedIterator};
160 use core::mem::{swap, size_of, ManuallyDrop};
165 use vec::{self, Vec};
167 use super::SpecExtend;
169 /// A priority queue implemented with a binary heap.
171 /// This will be a max-heap.
173 /// It is a logic error for an item to be modified in such a way that the
174 /// item's ordering relative to any other item, as determined by the `Ord`
175 /// trait, changes while it is in the heap. This is normally only possible
176 /// through `Cell`, `RefCell`, global state, I/O, or unsafe code.
181 /// use std::collections::BinaryHeap;
183 /// // Type inference lets us omit an explicit type signature (which
184 /// // would be `BinaryHeap<i32>` in this example).
185 /// let mut heap = BinaryHeap::new();
187 /// // We can use peek to look at the next item in the heap. In this case,
188 /// // there's no items in there yet so we get None.
189 /// assert_eq!(heap.peek(), None);
191 /// // Let's add some scores...
196 /// // Now peek shows the most important item in the heap.
197 /// assert_eq!(heap.peek(), Some(&5));
199 /// // We can check the length of a heap.
200 /// assert_eq!(heap.len(), 3);
202 /// // We can iterate over the items in the heap, although they are returned in
203 /// // a random order.
205 /// println!("{}", x);
208 /// // If we instead pop these scores, they should come back in order.
209 /// assert_eq!(heap.pop(), Some(5));
210 /// assert_eq!(heap.pop(), Some(2));
211 /// assert_eq!(heap.pop(), Some(1));
212 /// assert_eq!(heap.pop(), None);
214 /// // We can clear the heap of any remaining items.
217 /// // The heap should now be empty.
218 /// assert!(heap.is_empty())
220 #[stable(feature = "rust1", since = "1.0.0")]
221 pub struct BinaryHeap<T> {
225 /// Structure wrapping a mutable reference to the greatest item on a
228 /// This `struct` is created by the [`peek_mut`] method on [`BinaryHeap`]. See
229 /// its documentation for more.
231 /// [`peek_mut`]: struct.BinaryHeap.html#method.peek_mut
232 /// [`BinaryHeap`]: struct.BinaryHeap.html
233 #[stable(feature = "binary_heap_peek_mut", since = "1.12.0")]
234 pub struct PeekMut<'a, T: 'a + Ord> {
235 heap: &'a mut BinaryHeap<T>,
239 #[stable(feature = "collection_debug", since = "1.17.0")]
240 impl<'a, T: Ord + fmt::Debug> fmt::Debug for PeekMut<'a, T> {
241 fn fmt(&self, f: &mut fmt::Formatter) -> fmt::Result {
242 f.debug_tuple("PeekMut")
243 .field(&self.heap.data[0])
248 #[stable(feature = "binary_heap_peek_mut", since = "1.12.0")]
249 impl<'a, T: Ord> Drop for PeekMut<'a, T> {
252 self.heap.sift_down(0);
257 #[stable(feature = "binary_heap_peek_mut", since = "1.12.0")]
258 impl<'a, T: Ord> Deref for PeekMut<'a, T> {
260 fn deref(&self) -> &T {
265 #[stable(feature = "binary_heap_peek_mut", since = "1.12.0")]
266 impl<'a, T: Ord> DerefMut for PeekMut<'a, T> {
267 fn deref_mut(&mut self) -> &mut T {
268 &mut self.heap.data[0]
272 impl<'a, T: Ord> PeekMut<'a, T> {
273 /// Removes the peeked value from the heap and returns it.
274 #[stable(feature = "binary_heap_peek_mut_pop", since = "1.18.0")]
275 pub fn pop(mut this: PeekMut<'a, T>) -> T {
276 let value = this.heap.pop().unwrap();
282 #[stable(feature = "rust1", since = "1.0.0")]
283 impl<T: Clone> Clone for BinaryHeap<T> {
284 fn clone(&self) -> Self {
285 BinaryHeap { data: self.data.clone() }
288 fn clone_from(&mut self, source: &Self) {
289 self.data.clone_from(&source.data);
293 #[stable(feature = "rust1", since = "1.0.0")]
294 impl<T: Ord> Default for BinaryHeap<T> {
295 /// Creates an empty `BinaryHeap<T>`.
297 fn default() -> BinaryHeap<T> {
302 #[stable(feature = "binaryheap_debug", since = "1.4.0")]
303 impl<T: fmt::Debug + Ord> fmt::Debug for BinaryHeap<T> {
304 fn fmt(&self, f: &mut fmt::Formatter) -> fmt::Result {
305 f.debug_list().entries(self.iter()).finish()
309 impl<T: Ord> BinaryHeap<T> {
310 /// Creates an empty `BinaryHeap` as a max-heap.
317 /// use std::collections::BinaryHeap;
318 /// let mut heap = BinaryHeap::new();
321 #[stable(feature = "rust1", since = "1.0.0")]
322 pub fn new() -> BinaryHeap<T> {
323 BinaryHeap { data: vec![] }
326 /// Creates an empty `BinaryHeap` with a specific capacity.
327 /// This preallocates enough memory for `capacity` elements,
328 /// so that the `BinaryHeap` does not have to be reallocated
329 /// until it contains at least that many values.
336 /// use std::collections::BinaryHeap;
337 /// let mut heap = BinaryHeap::with_capacity(10);
340 #[stable(feature = "rust1", since = "1.0.0")]
341 pub fn with_capacity(capacity: usize) -> BinaryHeap<T> {
342 BinaryHeap { data: Vec::with_capacity(capacity) }
345 /// Returns an iterator visiting all values in the underlying vector, in
353 /// use std::collections::BinaryHeap;
354 /// let heap = BinaryHeap::from(vec![1, 2, 3, 4]);
356 /// // Print 1, 2, 3, 4 in arbitrary order
357 /// for x in heap.iter() {
358 /// println!("{}", x);
361 #[stable(feature = "rust1", since = "1.0.0")]
362 pub fn iter(&self) -> Iter<T> {
363 Iter { iter: self.data.iter() }
366 /// Returns the greatest item in the binary heap, or `None` if it is empty.
373 /// use std::collections::BinaryHeap;
374 /// let mut heap = BinaryHeap::new();
375 /// assert_eq!(heap.peek(), None);
380 /// assert_eq!(heap.peek(), Some(&5));
383 #[stable(feature = "rust1", since = "1.0.0")]
384 pub fn peek(&self) -> Option<&T> {
388 /// Returns a mutable reference to the greatest item in the binary heap, or
389 /// `None` if it is empty.
391 /// Note: If the `PeekMut` value is leaked, the heap may be in an
392 /// inconsistent state.
399 /// use std::collections::BinaryHeap;
400 /// let mut heap = BinaryHeap::new();
401 /// assert!(heap.peek_mut().is_none());
407 /// let mut val = heap.peek_mut().unwrap();
410 /// assert_eq!(heap.peek(), Some(&2));
412 #[stable(feature = "binary_heap_peek_mut", since = "1.12.0")]
413 pub fn peek_mut(&mut self) -> Option<PeekMut<T>> {
424 /// Returns the number of elements the binary heap can hold without reallocating.
431 /// use std::collections::BinaryHeap;
432 /// let mut heap = BinaryHeap::with_capacity(100);
433 /// assert!(heap.capacity() >= 100);
436 #[stable(feature = "rust1", since = "1.0.0")]
437 pub fn capacity(&self) -> usize {
441 /// Reserves the minimum capacity for exactly `additional` more elements to be inserted in the
442 /// given `BinaryHeap`. Does nothing if the capacity is already sufficient.
444 /// Note that the allocator may give the collection more space than it requests. Therefore
445 /// capacity can not be relied upon to be precisely minimal. Prefer [`reserve`] if future
446 /// insertions are expected.
450 /// Panics if the new capacity overflows `usize`.
457 /// use std::collections::BinaryHeap;
458 /// let mut heap = BinaryHeap::new();
459 /// heap.reserve_exact(100);
460 /// assert!(heap.capacity() >= 100);
464 /// [`reserve`]: #method.reserve
465 #[stable(feature = "rust1", since = "1.0.0")]
466 pub fn reserve_exact(&mut self, additional: usize) {
467 self.data.reserve_exact(additional);
470 /// Reserves capacity for at least `additional` more elements to be inserted in the
471 /// `BinaryHeap`. The collection may reserve more space to avoid frequent reallocations.
475 /// Panics if the new capacity overflows `usize`.
482 /// use std::collections::BinaryHeap;
483 /// let mut heap = BinaryHeap::new();
484 /// heap.reserve(100);
485 /// assert!(heap.capacity() >= 100);
488 #[stable(feature = "rust1", since = "1.0.0")]
489 pub fn reserve(&mut self, additional: usize) {
490 self.data.reserve(additional);
493 /// Discards as much additional capacity as possible.
500 /// use std::collections::BinaryHeap;
501 /// let mut heap: BinaryHeap<i32> = BinaryHeap::with_capacity(100);
503 /// assert!(heap.capacity() >= 100);
504 /// heap.shrink_to_fit();
505 /// assert!(heap.capacity() == 0);
507 #[stable(feature = "rust1", since = "1.0.0")]
508 pub fn shrink_to_fit(&mut self) {
509 self.data.shrink_to_fit();
512 /// Discards capacity with a lower bound.
514 /// The capacity will remain at least as large as both the length
515 /// and the supplied value.
517 /// Panics if the current capacity is smaller than the supplied
518 /// minimum capacity.
523 /// #![feature(shrink_to)]
524 /// use std::collections::BinaryHeap;
525 /// let mut heap: BinaryHeap<i32> = BinaryHeap::with_capacity(100);
527 /// assert!(heap.capacity() >= 100);
528 /// heap.shrink_to(10);
529 /// assert!(heap.capacity() >= 10);
532 #[unstable(feature = "shrink_to", reason = "new API", issue="56431")]
533 pub fn shrink_to(&mut self, min_capacity: usize) {
534 self.data.shrink_to(min_capacity)
537 /// Removes the greatest item from the binary heap and returns it, or `None` if it
545 /// use std::collections::BinaryHeap;
546 /// let mut heap = BinaryHeap::from(vec![1, 3]);
548 /// assert_eq!(heap.pop(), Some(3));
549 /// assert_eq!(heap.pop(), Some(1));
550 /// assert_eq!(heap.pop(), None);
552 #[stable(feature = "rust1", since = "1.0.0")]
553 pub fn pop(&mut self) -> Option<T> {
554 self.data.pop().map(|mut item| {
555 if !self.is_empty() {
556 swap(&mut item, &mut self.data[0]);
557 self.sift_down_to_bottom(0);
563 /// Pushes an item onto the binary heap.
570 /// use std::collections::BinaryHeap;
571 /// let mut heap = BinaryHeap::new();
576 /// assert_eq!(heap.len(), 3);
577 /// assert_eq!(heap.peek(), Some(&5));
579 #[stable(feature = "rust1", since = "1.0.0")]
580 pub fn push(&mut self, item: T) {
581 let old_len = self.len();
582 self.data.push(item);
583 self.sift_up(0, old_len);
586 /// Consumes the `BinaryHeap` and returns the underlying vector
587 /// in arbitrary order.
594 /// use std::collections::BinaryHeap;
595 /// let heap = BinaryHeap::from(vec![1, 2, 3, 4, 5, 6, 7]);
596 /// let vec = heap.into_vec();
598 /// // Will print in some order
600 /// println!("{}", x);
603 #[stable(feature = "binary_heap_extras_15", since = "1.5.0")]
604 pub fn into_vec(self) -> Vec<T> {
608 /// Consumes the `BinaryHeap` and returns a vector in sorted
609 /// (ascending) order.
616 /// use std::collections::BinaryHeap;
618 /// let mut heap = BinaryHeap::from(vec![1, 2, 4, 5, 7]);
622 /// let vec = heap.into_sorted_vec();
623 /// assert_eq!(vec, [1, 2, 3, 4, 5, 6, 7]);
625 #[stable(feature = "binary_heap_extras_15", since = "1.5.0")]
626 pub fn into_sorted_vec(mut self) -> Vec<T> {
627 let mut end = self.len();
630 self.data.swap(0, end);
631 self.sift_down_range(0, end);
636 // The implementations of sift_up and sift_down use unsafe blocks in
637 // order to move an element out of the vector (leaving behind a
638 // hole), shift along the others and move the removed element back into the
639 // vector at the final location of the hole.
640 // The `Hole` type is used to represent this, and make sure
641 // the hole is filled back at the end of its scope, even on panic.
642 // Using a hole reduces the constant factor compared to using swaps,
643 // which involves twice as many moves.
644 fn sift_up(&mut self, start: usize, pos: usize) -> usize {
646 // Take out the value at `pos` and create a hole.
647 let mut hole = Hole::new(&mut self.data, pos);
649 while hole.pos() > start {
650 let parent = (hole.pos() - 1) / 2;
651 if hole.element() <= hole.get(parent) {
654 hole.move_to(parent);
660 /// Take an element at `pos` and move it down the heap,
661 /// while its children are larger.
662 fn sift_down_range(&mut self, pos: usize, end: usize) {
664 let mut hole = Hole::new(&mut self.data, pos);
665 let mut child = 2 * pos + 1;
667 let right = child + 1;
668 // compare with the greater of the two children
669 if right < end && !(hole.get(child) > hole.get(right)) {
672 // if we are already in order, stop.
673 if hole.element() >= hole.get(child) {
677 child = 2 * hole.pos() + 1;
682 fn sift_down(&mut self, pos: usize) {
683 let len = self.len();
684 self.sift_down_range(pos, len);
687 /// Take an element at `pos` and move it all the way down the heap,
688 /// then sift it up to its position.
690 /// Note: This is faster when the element is known to be large / should
691 /// be closer to the bottom.
692 fn sift_down_to_bottom(&mut self, mut pos: usize) {
693 let end = self.len();
696 let mut hole = Hole::new(&mut self.data, pos);
697 let mut child = 2 * pos + 1;
699 let right = child + 1;
700 // compare with the greater of the two children
701 if right < end && !(hole.get(child) > hole.get(right)) {
705 child = 2 * hole.pos() + 1;
709 self.sift_up(start, pos);
712 /// Returns the length of the binary heap.
719 /// use std::collections::BinaryHeap;
720 /// let heap = BinaryHeap::from(vec![1, 3]);
722 /// assert_eq!(heap.len(), 2);
724 #[stable(feature = "rust1", since = "1.0.0")]
725 pub fn len(&self) -> usize {
729 /// Checks if the binary heap is empty.
736 /// use std::collections::BinaryHeap;
737 /// let mut heap = BinaryHeap::new();
739 /// assert!(heap.is_empty());
745 /// assert!(!heap.is_empty());
747 #[stable(feature = "rust1", since = "1.0.0")]
748 pub fn is_empty(&self) -> bool {
752 /// Clears the binary heap, returning an iterator over the removed elements.
754 /// The elements are removed in arbitrary order.
761 /// use std::collections::BinaryHeap;
762 /// let mut heap = BinaryHeap::from(vec![1, 3]);
764 /// assert!(!heap.is_empty());
766 /// for x in heap.drain() {
767 /// println!("{}", x);
770 /// assert!(heap.is_empty());
773 #[stable(feature = "drain", since = "1.6.0")]
774 pub fn drain(&mut self) -> Drain<T> {
775 Drain { iter: self.data.drain(..) }
778 /// Drops all items from the binary heap.
785 /// use std::collections::BinaryHeap;
786 /// let mut heap = BinaryHeap::from(vec![1, 3]);
788 /// assert!(!heap.is_empty());
792 /// assert!(heap.is_empty());
794 #[stable(feature = "rust1", since = "1.0.0")]
795 pub fn clear(&mut self) {
799 fn rebuild(&mut self) {
800 let mut n = self.len() / 2;
807 /// Moves all the elements of `other` into `self`, leaving `other` empty.
814 /// use std::collections::BinaryHeap;
816 /// let v = vec![-10, 1, 2, 3, 3];
817 /// let mut a = BinaryHeap::from(v);
819 /// let v = vec![-20, 5, 43];
820 /// let mut b = BinaryHeap::from(v);
822 /// a.append(&mut b);
824 /// assert_eq!(a.into_sorted_vec(), [-20, -10, 1, 2, 3, 3, 5, 43]);
825 /// assert!(b.is_empty());
827 #[stable(feature = "binary_heap_append", since = "1.11.0")]
828 pub fn append(&mut self, other: &mut Self) {
829 if self.len() < other.len() {
833 if other.is_empty() {
838 fn log2_fast(x: usize) -> usize {
839 8 * size_of::<usize>() - (x.leading_zeros() as usize) - 1
842 // `rebuild` takes O(len1 + len2) operations
843 // and about 2 * (len1 + len2) comparisons in the worst case
844 // while `extend` takes O(len2 * log_2(len1)) operations
845 // and about 1 * len2 * log_2(len1) comparisons in the worst case,
846 // assuming len1 >= len2.
848 fn better_to_rebuild(len1: usize, len2: usize) -> bool {
849 2 * (len1 + len2) < len2 * log2_fast(len1)
852 if better_to_rebuild(self.len(), other.len()) {
853 self.data.append(&mut other.data);
856 self.extend(other.drain());
861 /// Hole represents a hole in a slice i.e. an index without valid value
862 /// (because it was moved from or duplicated).
863 /// In drop, `Hole` will restore the slice by filling the hole
864 /// position with the value that was originally removed.
865 struct Hole<'a, T: 'a> {
867 elt: ManuallyDrop<T>,
871 impl<'a, T> Hole<'a, T> {
872 /// Create a new Hole at index `pos`.
874 /// Unsafe because pos must be within the data slice.
876 unsafe fn new(data: &'a mut [T], pos: usize) -> Self {
877 debug_assert!(pos < data.len());
878 let elt = ptr::read(&data[pos]);
881 elt: ManuallyDrop::new(elt),
887 fn pos(&self) -> usize {
891 /// Returns a reference to the element removed.
893 fn element(&self) -> &T {
897 /// Returns a reference to the element at `index`.
899 /// Unsafe because index must be within the data slice and not equal to pos.
901 unsafe fn get(&self, index: usize) -> &T {
902 debug_assert!(index != self.pos);
903 debug_assert!(index < self.data.len());
904 self.data.get_unchecked(index)
907 /// Move hole to new location
909 /// Unsafe because index must be within the data slice and not equal to pos.
911 unsafe fn move_to(&mut self, index: usize) {
912 debug_assert!(index != self.pos);
913 debug_assert!(index < self.data.len());
914 let index_ptr: *const _ = self.data.get_unchecked(index);
915 let hole_ptr = self.data.get_unchecked_mut(self.pos);
916 ptr::copy_nonoverlapping(index_ptr, hole_ptr, 1);
921 impl<'a, T> Drop for Hole<'a, T> {
924 // fill the hole again
927 ptr::copy_nonoverlapping(&*self.elt, self.data.get_unchecked_mut(pos), 1);
932 /// An iterator over the elements of a `BinaryHeap`.
934 /// This `struct` is created by the [`iter`] method on [`BinaryHeap`]. See its
935 /// documentation for more.
937 /// [`iter`]: struct.BinaryHeap.html#method.iter
938 /// [`BinaryHeap`]: struct.BinaryHeap.html
939 #[stable(feature = "rust1", since = "1.0.0")]
940 pub struct Iter<'a, T: 'a> {
941 iter: slice::Iter<'a, T>,
944 #[stable(feature = "collection_debug", since = "1.17.0")]
945 impl<'a, T: 'a + fmt::Debug> fmt::Debug for Iter<'a, T> {
946 fn fmt(&self, f: &mut fmt::Formatter) -> fmt::Result {
947 f.debug_tuple("Iter")
948 .field(&self.iter.as_slice())
953 // FIXME(#26925) Remove in favor of `#[derive(Clone)]`
954 #[stable(feature = "rust1", since = "1.0.0")]
955 impl<'a, T> Clone for Iter<'a, T> {
956 fn clone(&self) -> Iter<'a, T> {
957 Iter { iter: self.iter.clone() }
961 #[stable(feature = "rust1", since = "1.0.0")]
962 impl<'a, T> Iterator for Iter<'a, T> {
966 fn next(&mut self) -> Option<&'a T> {
971 fn size_hint(&self) -> (usize, Option<usize>) {
972 self.iter.size_hint()
976 #[stable(feature = "rust1", since = "1.0.0")]
977 impl<'a, T> DoubleEndedIterator for Iter<'a, T> {
979 fn next_back(&mut self) -> Option<&'a T> {
980 self.iter.next_back()
984 #[stable(feature = "rust1", since = "1.0.0")]
985 impl<'a, T> ExactSizeIterator for Iter<'a, T> {
986 fn is_empty(&self) -> bool {
991 #[stable(feature = "fused", since = "1.26.0")]
992 impl<'a, T> FusedIterator for Iter<'a, T> {}
994 /// An owning iterator over the elements of a `BinaryHeap`.
996 /// This `struct` is created by the [`into_iter`] method on [`BinaryHeap`][`BinaryHeap`]
997 /// (provided by the `IntoIterator` trait). See its documentation for more.
999 /// [`into_iter`]: struct.BinaryHeap.html#method.into_iter
1000 /// [`BinaryHeap`]: struct.BinaryHeap.html
1001 #[stable(feature = "rust1", since = "1.0.0")]
1003 pub struct IntoIter<T> {
1004 iter: vec::IntoIter<T>,
1007 #[stable(feature = "collection_debug", since = "1.17.0")]
1008 impl<T: fmt::Debug> fmt::Debug for IntoIter<T> {
1009 fn fmt(&self, f: &mut fmt::Formatter) -> fmt::Result {
1010 f.debug_tuple("IntoIter")
1011 .field(&self.iter.as_slice())
1016 #[stable(feature = "rust1", since = "1.0.0")]
1017 impl<T> Iterator for IntoIter<T> {
1021 fn next(&mut self) -> Option<T> {
1026 fn size_hint(&self) -> (usize, Option<usize>) {
1027 self.iter.size_hint()
1031 #[stable(feature = "rust1", since = "1.0.0")]
1032 impl<T> DoubleEndedIterator for IntoIter<T> {
1034 fn next_back(&mut self) -> Option<T> {
1035 self.iter.next_back()
1039 #[stable(feature = "rust1", since = "1.0.0")]
1040 impl<T> ExactSizeIterator for IntoIter<T> {
1041 fn is_empty(&self) -> bool {
1042 self.iter.is_empty()
1046 #[stable(feature = "fused", since = "1.26.0")]
1047 impl<T> FusedIterator for IntoIter<T> {}
1049 /// A draining iterator over the elements of a `BinaryHeap`.
1051 /// This `struct` is created by the [`drain`] method on [`BinaryHeap`]. See its
1052 /// documentation for more.
1054 /// [`drain`]: struct.BinaryHeap.html#method.drain
1055 /// [`BinaryHeap`]: struct.BinaryHeap.html
1056 #[stable(feature = "drain", since = "1.6.0")]
1058 pub struct Drain<'a, T: 'a> {
1059 iter: vec::Drain<'a, T>,
1062 #[stable(feature = "drain", since = "1.6.0")]
1063 impl<'a, T: 'a> Iterator for Drain<'a, T> {
1067 fn next(&mut self) -> Option<T> {
1072 fn size_hint(&self) -> (usize, Option<usize>) {
1073 self.iter.size_hint()
1077 #[stable(feature = "drain", since = "1.6.0")]
1078 impl<'a, T: 'a> DoubleEndedIterator for Drain<'a, T> {
1080 fn next_back(&mut self) -> Option<T> {
1081 self.iter.next_back()
1085 #[stable(feature = "drain", since = "1.6.0")]
1086 impl<'a, T: 'a> ExactSizeIterator for Drain<'a, T> {
1087 fn is_empty(&self) -> bool {
1088 self.iter.is_empty()
1092 #[stable(feature = "fused", since = "1.26.0")]
1093 impl<'a, T: 'a> FusedIterator for Drain<'a, T> {}
1095 #[stable(feature = "binary_heap_extras_15", since = "1.5.0")]
1096 impl<T: Ord> From<Vec<T>> for BinaryHeap<T> {
1097 fn from(vec: Vec<T>) -> BinaryHeap<T> {
1098 let mut heap = BinaryHeap { data: vec };
1104 #[stable(feature = "binary_heap_extras_15", since = "1.5.0")]
1105 impl<T> From<BinaryHeap<T>> for Vec<T> {
1106 fn from(heap: BinaryHeap<T>) -> Vec<T> {
1111 #[stable(feature = "rust1", since = "1.0.0")]
1112 impl<T: Ord> FromIterator<T> for BinaryHeap<T> {
1113 fn from_iter<I: IntoIterator<Item = T>>(iter: I) -> BinaryHeap<T> {
1114 BinaryHeap::from(iter.into_iter().collect::<Vec<_>>())
1118 #[stable(feature = "rust1", since = "1.0.0")]
1119 impl<T: Ord> IntoIterator for BinaryHeap<T> {
1121 type IntoIter = IntoIter<T>;
1123 /// Creates a consuming iterator, that is, one that moves each value out of
1124 /// the binary heap in arbitrary order. The binary heap cannot be used
1125 /// after calling this.
1132 /// use std::collections::BinaryHeap;
1133 /// let heap = BinaryHeap::from(vec![1, 2, 3, 4]);
1135 /// // Print 1, 2, 3, 4 in arbitrary order
1136 /// for x in heap.into_iter() {
1137 /// // x has type i32, not &i32
1138 /// println!("{}", x);
1141 fn into_iter(self) -> IntoIter<T> {
1142 IntoIter { iter: self.data.into_iter() }
1146 #[stable(feature = "rust1", since = "1.0.0")]
1147 impl<'a, T> IntoIterator for &'a BinaryHeap<T>
1151 type IntoIter = Iter<'a, T>;
1153 fn into_iter(self) -> Iter<'a, T> {
1158 #[stable(feature = "rust1", since = "1.0.0")]
1159 impl<T: Ord> Extend<T> for BinaryHeap<T> {
1161 fn extend<I: IntoIterator<Item = T>>(&mut self, iter: I) {
1162 <Self as SpecExtend<I>>::spec_extend(self, iter);
1166 impl<T: Ord, I: IntoIterator<Item = T>> SpecExtend<I> for BinaryHeap<T> {
1167 default fn spec_extend(&mut self, iter: I) {
1168 self.extend_desugared(iter.into_iter());
1172 impl<T: Ord> SpecExtend<BinaryHeap<T>> for BinaryHeap<T> {
1173 fn spec_extend(&mut self, ref mut other: BinaryHeap<T>) {
1178 impl<T: Ord> BinaryHeap<T> {
1179 fn extend_desugared<I: IntoIterator<Item = T>>(&mut self, iter: I) {
1180 let iterator = iter.into_iter();
1181 let (lower, _) = iterator.size_hint();
1183 self.reserve(lower);
1185 for elem in iterator {
1191 #[stable(feature = "extend_ref", since = "1.2.0")]
1192 impl<'a, T: 'a + Ord + Copy> Extend<&'a T> for BinaryHeap<T> {
1193 fn extend<I: IntoIterator<Item = &'a T>>(&mut self, iter: I) {
1194 self.extend(iter.into_iter().cloned());