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 here
47 //! other.cost.cmp(&self.cost)
51 //! // `PartialOrd` needs to be implemented as well.
52 //! impl PartialOrd for State {
53 //! fn partial_cmp(&self, other: &State) -> Option<Ordering> {
54 //! Some(self.cmp(other))
58 //! // Each node is represented as an `usize`, for a shorter implementation.
64 //! // Dijkstra's shortest path algorithm.
66 //! // Start at `start` and use `dist` to track the current shortest distance
67 //! // to each node. This implementation isn't memory-efficient as it may leave duplicate
68 //! // nodes in the queue. It also uses `usize::MAX` as a sentinel value,
69 //! // for a simpler implementation.
70 //! fn shortest_path(adj_list: &Vec<Vec<Edge>>, start: usize, goal: usize) -> Option<usize> {
71 //! // dist[node] = current shortest distance from `start` to `node`
72 //! let mut dist: Vec<_> = (0..adj_list.len()).map(|_| usize::MAX).collect();
74 //! let mut heap = BinaryHeap::new();
76 //! // We're at `start`, with a zero cost
78 //! heap.push(State { cost: 0, position: start });
80 //! // Examine the frontier with lower cost nodes first (min-heap)
81 //! while let Some(State { cost, position }) = heap.pop() {
82 //! // Alternatively we could have continued to find all shortest paths
83 //! if position == goal { return Some(cost); }
85 //! // Important as we may have already found a better way
86 //! if cost > dist[position] { continue; }
88 //! // For each node we can reach, see if we can find a way with
89 //! // a lower cost going through this node
90 //! for edge in &adj_list[position] {
91 //! let next = State { cost: cost + edge.cost, position: edge.node };
93 //! // If so, add it to the frontier and continue
94 //! if next.cost < dist[next.position] {
96 //! // Relaxation, we have now found a better way
97 //! dist[next.position] = next.cost;
102 //! // Goal not reachable
107 //! // This is the directed graph we're going to use.
108 //! // The node numbers correspond to the different states,
109 //! // and the edge weights symbolize the cost of moving
110 //! // from one node to another.
111 //! // Note that the edges are one-way.
114 //! // +-----------------+
117 //! // 0 -----> 1 -----> 3 ---> 4
121 //! // +------> 2 -------+ |
123 //! // +---------------+
125 //! // The graph is represented as an adjacency list where each index,
126 //! // corresponding to a node value, has a list of outgoing edges.
127 //! // Chosen for its efficiency.
128 //! let graph = vec![
130 //! vec![Edge { node: 2, cost: 10 },
131 //! Edge { node: 1, cost: 1 }],
133 //! vec![Edge { node: 3, cost: 2 }],
135 //! vec![Edge { node: 1, cost: 1 },
136 //! Edge { node: 3, cost: 3 },
137 //! Edge { node: 4, cost: 1 }],
139 //! vec![Edge { node: 0, cost: 7 },
140 //! Edge { node: 4, cost: 2 }],
144 //! assert_eq!(shortest_path(&graph, 0, 1), Some(1));
145 //! assert_eq!(shortest_path(&graph, 0, 3), Some(3));
146 //! assert_eq!(shortest_path(&graph, 3, 0), Some(7));
147 //! assert_eq!(shortest_path(&graph, 0, 4), Some(5));
148 //! assert_eq!(shortest_path(&graph, 4, 0), None);
152 #![allow(missing_docs)]
153 #![stable(feature = "rust1", since = "1.0.0")]
155 use core::ops::{Deref, DerefMut, Place, Placer, InPlace};
156 use core::iter::{FromIterator, FusedIterator};
157 use core::mem::{swap, 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 /// Structure wrapping a mutable reference to the greatest item on a
225 /// This `struct` is created by the [`peek_mut`] method on [`BinaryHeap`]. See
226 /// its documentation for more.
228 /// [`peek_mut`]: struct.BinaryHeap.html#method.peek_mut
229 /// [`BinaryHeap`]: struct.BinaryHeap.html
230 #[stable(feature = "binary_heap_peek_mut", since = "1.12.0")]
231 pub struct PeekMut<'a, T: 'a + Ord> {
232 heap: &'a mut BinaryHeap<T>,
236 #[stable(feature = "collection_debug", since = "1.17.0")]
237 impl<'a, T: Ord + fmt::Debug> fmt::Debug for PeekMut<'a, T> {
238 fn fmt(&self, f: &mut fmt::Formatter) -> fmt::Result {
239 f.debug_tuple("PeekMut")
240 .field(&self.heap.data[0])
245 #[stable(feature = "binary_heap_peek_mut", since = "1.12.0")]
246 impl<'a, T: Ord> Drop for PeekMut<'a, T> {
249 self.heap.sift_down(0);
254 #[stable(feature = "binary_heap_peek_mut", since = "1.12.0")]
255 impl<'a, T: Ord> Deref for PeekMut<'a, T> {
257 fn deref(&self) -> &T {
262 #[stable(feature = "binary_heap_peek_mut", since = "1.12.0")]
263 impl<'a, T: Ord> DerefMut for PeekMut<'a, T> {
264 fn deref_mut(&mut self) -> &mut T {
265 &mut self.heap.data[0]
269 impl<'a, T: Ord> PeekMut<'a, T> {
270 /// Removes the peeked value from the heap and returns it.
271 #[unstable(feature = "binary_heap_peek_mut_pop", issue = "38863")]
272 pub fn pop(mut this: PeekMut<'a, T>) -> T {
273 let value = this.heap.pop().unwrap();
279 #[stable(feature = "rust1", since = "1.0.0")]
280 impl<T: Clone> Clone for BinaryHeap<T> {
281 fn clone(&self) -> Self {
282 BinaryHeap { data: self.data.clone() }
285 fn clone_from(&mut self, source: &Self) {
286 self.data.clone_from(&source.data);
290 #[stable(feature = "rust1", since = "1.0.0")]
291 impl<T: Ord> Default for BinaryHeap<T> {
292 /// Creates an empty `BinaryHeap<T>`.
294 fn default() -> BinaryHeap<T> {
299 #[stable(feature = "binaryheap_debug", since = "1.4.0")]
300 impl<T: fmt::Debug + Ord> fmt::Debug for BinaryHeap<T> {
301 fn fmt(&self, f: &mut fmt::Formatter) -> fmt::Result {
302 f.debug_list().entries(self.iter()).finish()
306 impl<T: Ord> BinaryHeap<T> {
307 /// Creates an empty `BinaryHeap` as a max-heap.
314 /// use std::collections::BinaryHeap;
315 /// let mut heap = BinaryHeap::new();
318 #[stable(feature = "rust1", since = "1.0.0")]
319 pub fn new() -> BinaryHeap<T> {
320 BinaryHeap { data: vec![] }
323 /// Creates an empty `BinaryHeap` with a specific capacity.
324 /// This preallocates enough memory for `capacity` elements,
325 /// so that the `BinaryHeap` does not have to be reallocated
326 /// until it contains at least that many values.
333 /// use std::collections::BinaryHeap;
334 /// let mut heap = BinaryHeap::with_capacity(10);
337 #[stable(feature = "rust1", since = "1.0.0")]
338 pub fn with_capacity(capacity: usize) -> BinaryHeap<T> {
339 BinaryHeap { data: Vec::with_capacity(capacity) }
342 /// Returns an iterator visiting all values in the underlying vector, in
350 /// use std::collections::BinaryHeap;
351 /// let heap = BinaryHeap::from(vec![1, 2, 3, 4]);
353 /// // Print 1, 2, 3, 4 in arbitrary order
354 /// for x in heap.iter() {
355 /// println!("{}", x);
358 #[stable(feature = "rust1", since = "1.0.0")]
359 pub fn iter(&self) -> Iter<T> {
360 Iter { iter: self.data.iter() }
363 /// Returns the greatest item in the binary heap, or `None` if it is empty.
370 /// use std::collections::BinaryHeap;
371 /// let mut heap = BinaryHeap::new();
372 /// assert_eq!(heap.peek(), None);
377 /// assert_eq!(heap.peek(), Some(&5));
380 #[stable(feature = "rust1", since = "1.0.0")]
381 pub fn peek(&self) -> Option<&T> {
385 /// Returns a mutable reference to the greatest item in the binary heap, or
386 /// `None` if it is empty.
388 /// Note: If the `PeekMut` value is leaked, the heap may be in an
389 /// inconsistent state.
396 /// use std::collections::BinaryHeap;
397 /// let mut heap = BinaryHeap::new();
398 /// assert!(heap.peek_mut().is_none());
404 /// let mut val = heap.peek_mut().unwrap();
407 /// assert_eq!(heap.peek(), Some(&2));
409 #[stable(feature = "binary_heap_peek_mut", since = "1.12.0")]
410 pub fn peek_mut(&mut self) -> Option<PeekMut<T>> {
421 /// Returns the number of elements the binary heap can hold without reallocating.
428 /// use std::collections::BinaryHeap;
429 /// let mut heap = BinaryHeap::with_capacity(100);
430 /// assert!(heap.capacity() >= 100);
433 #[stable(feature = "rust1", since = "1.0.0")]
434 pub fn capacity(&self) -> usize {
438 /// Reserves the minimum capacity for exactly `additional` more elements to be inserted in the
439 /// given `BinaryHeap`. Does nothing if the capacity is already sufficient.
441 /// Note that the allocator may give the collection more space than it requests. Therefore
442 /// capacity can not be relied upon to be precisely minimal. Prefer [`reserve`] if future
443 /// insertions are expected.
447 /// Panics if the new capacity overflows `usize`.
454 /// use std::collections::BinaryHeap;
455 /// let mut heap = BinaryHeap::new();
456 /// heap.reserve_exact(100);
457 /// assert!(heap.capacity() >= 100);
461 /// [`reserve`]: #method.reserve
462 #[stable(feature = "rust1", since = "1.0.0")]
463 pub fn reserve_exact(&mut self, additional: usize) {
464 self.data.reserve_exact(additional);
467 /// Reserves capacity for at least `additional` more elements to be inserted in the
468 /// `BinaryHeap`. The collection may reserve more space to avoid frequent reallocations.
472 /// Panics if the new capacity overflows `usize`.
479 /// use std::collections::BinaryHeap;
480 /// let mut heap = BinaryHeap::new();
481 /// heap.reserve(100);
482 /// assert!(heap.capacity() >= 100);
485 #[stable(feature = "rust1", since = "1.0.0")]
486 pub fn reserve(&mut self, additional: usize) {
487 self.data.reserve(additional);
490 /// Discards as much additional capacity as possible.
497 /// use std::collections::BinaryHeap;
498 /// let mut heap: BinaryHeap<i32> = BinaryHeap::with_capacity(100);
500 /// assert!(heap.capacity() >= 100);
501 /// heap.shrink_to_fit();
502 /// assert!(heap.capacity() == 0);
504 #[stable(feature = "rust1", since = "1.0.0")]
505 pub fn shrink_to_fit(&mut self) {
506 self.data.shrink_to_fit();
509 /// Removes the greatest item from the binary heap and returns it, or `None` if it
517 /// use std::collections::BinaryHeap;
518 /// let mut heap = BinaryHeap::from(vec![1, 3]);
520 /// assert_eq!(heap.pop(), Some(3));
521 /// assert_eq!(heap.pop(), Some(1));
522 /// assert_eq!(heap.pop(), None);
524 #[stable(feature = "rust1", since = "1.0.0")]
525 pub fn pop(&mut self) -> Option<T> {
526 self.data.pop().map(|mut item| {
527 if !self.is_empty() {
528 swap(&mut item, &mut self.data[0]);
529 self.sift_down_to_bottom(0);
535 /// Pushes an item onto the binary heap.
542 /// use std::collections::BinaryHeap;
543 /// let mut heap = BinaryHeap::new();
548 /// assert_eq!(heap.len(), 3);
549 /// assert_eq!(heap.peek(), Some(&5));
551 #[stable(feature = "rust1", since = "1.0.0")]
552 pub fn push(&mut self, item: T) {
553 let old_len = self.len();
554 self.data.push(item);
555 self.sift_up(0, old_len);
558 /// Consumes the `BinaryHeap` and returns the underlying vector
559 /// in arbitrary order.
566 /// use std::collections::BinaryHeap;
567 /// let heap = BinaryHeap::from(vec![1, 2, 3, 4, 5, 6, 7]);
568 /// let vec = heap.into_vec();
570 /// // Will print in some order
572 /// println!("{}", x);
575 #[stable(feature = "binary_heap_extras_15", since = "1.5.0")]
576 pub fn into_vec(self) -> Vec<T> {
580 /// Consumes the `BinaryHeap` and returns a vector in sorted
581 /// (ascending) order.
588 /// use std::collections::BinaryHeap;
590 /// let mut heap = BinaryHeap::from(vec![1, 2, 4, 5, 7]);
594 /// let vec = heap.into_sorted_vec();
595 /// assert_eq!(vec, [1, 2, 3, 4, 5, 6, 7]);
597 #[stable(feature = "binary_heap_extras_15", since = "1.5.0")]
598 pub fn into_sorted_vec(mut self) -> Vec<T> {
599 let mut end = self.len();
602 self.data.swap(0, end);
603 self.sift_down_range(0, end);
608 // The implementations of sift_up and sift_down use unsafe blocks in
609 // order to move an element out of the vector (leaving behind a
610 // hole), shift along the others and move the removed element back into the
611 // vector at the final location of the hole.
612 // The `Hole` type is used to represent this, and make sure
613 // the hole is filled back at the end of its scope, even on panic.
614 // Using a hole reduces the constant factor compared to using swaps,
615 // which involves twice as many moves.
616 fn sift_up(&mut self, start: usize, pos: usize) -> usize {
618 // Take out the value at `pos` and create a hole.
619 let mut hole = Hole::new(&mut self.data, pos);
621 while hole.pos() > start {
622 let parent = (hole.pos() - 1) / 2;
623 if hole.element() <= hole.get(parent) {
626 hole.move_to(parent);
632 /// Take an element at `pos` and move it down the heap,
633 /// while its children are larger.
634 fn sift_down_range(&mut self, pos: usize, end: usize) {
636 let mut hole = Hole::new(&mut self.data, pos);
637 let mut child = 2 * pos + 1;
639 let right = child + 1;
640 // compare with the greater of the two children
641 if right < end && !(hole.get(child) > hole.get(right)) {
644 // if we are already in order, stop.
645 if hole.element() >= hole.get(child) {
649 child = 2 * hole.pos() + 1;
654 fn sift_down(&mut self, pos: usize) {
655 let len = self.len();
656 self.sift_down_range(pos, len);
659 /// Take an element at `pos` and move it all the way down the heap,
660 /// then sift it up to its position.
662 /// Note: This is faster when the element is known to be large / should
663 /// be closer to the bottom.
664 fn sift_down_to_bottom(&mut self, mut pos: usize) {
665 let end = self.len();
668 let mut hole = Hole::new(&mut self.data, pos);
669 let mut child = 2 * pos + 1;
671 let right = child + 1;
672 // compare with the greater of the two children
673 if right < end && !(hole.get(child) > hole.get(right)) {
677 child = 2 * hole.pos() + 1;
681 self.sift_up(start, pos);
684 /// Returns the length of the binary heap.
691 /// use std::collections::BinaryHeap;
692 /// let heap = BinaryHeap::from(vec![1, 3]);
694 /// assert_eq!(heap.len(), 2);
696 #[stable(feature = "rust1", since = "1.0.0")]
697 pub fn len(&self) -> usize {
701 /// Checks if the binary heap is empty.
708 /// use std::collections::BinaryHeap;
709 /// let mut heap = BinaryHeap::new();
711 /// assert!(heap.is_empty());
717 /// assert!(!heap.is_empty());
719 #[stable(feature = "rust1", since = "1.0.0")]
720 pub fn is_empty(&self) -> bool {
724 /// Clears the binary heap, returning an iterator over the removed elements.
726 /// The elements are removed in arbitrary order.
733 /// use std::collections::BinaryHeap;
734 /// let mut heap = BinaryHeap::from(vec![1, 3]);
736 /// assert!(!heap.is_empty());
738 /// for x in heap.drain() {
739 /// println!("{}", x);
742 /// assert!(heap.is_empty());
745 #[stable(feature = "drain", since = "1.6.0")]
746 pub fn drain(&mut self) -> Drain<T> {
747 Drain { iter: self.data.drain(..) }
750 /// Drops all items from the binary heap.
757 /// use std::collections::BinaryHeap;
758 /// let mut heap = BinaryHeap::from(vec![1, 3]);
760 /// assert!(!heap.is_empty());
764 /// assert!(heap.is_empty());
766 #[stable(feature = "rust1", since = "1.0.0")]
767 pub fn clear(&mut self) {
771 fn rebuild(&mut self) {
772 let mut n = self.len() / 2;
779 /// Moves all the elements of `other` into `self`, leaving `other` empty.
786 /// use std::collections::BinaryHeap;
788 /// let v = vec![-10, 1, 2, 3, 3];
789 /// let mut a = BinaryHeap::from(v);
791 /// let v = vec![-20, 5, 43];
792 /// let mut b = BinaryHeap::from(v);
794 /// a.append(&mut b);
796 /// assert_eq!(a.into_sorted_vec(), [-20, -10, 1, 2, 3, 3, 5, 43]);
797 /// assert!(b.is_empty());
799 #[stable(feature = "binary_heap_append", since = "1.11.0")]
800 pub fn append(&mut self, other: &mut Self) {
801 if self.len() < other.len() {
805 if other.is_empty() {
810 fn log2_fast(x: usize) -> usize {
811 8 * size_of::<usize>() - (x.leading_zeros() as usize) - 1
814 // `rebuild` takes O(len1 + len2) operations
815 // and about 2 * (len1 + len2) comparisons in the worst case
816 // while `extend` takes O(len2 * log_2(len1)) operations
817 // and about 1 * len2 * log_2(len1) comparisons in the worst case,
818 // assuming len1 >= len2.
820 fn better_to_rebuild(len1: usize, len2: usize) -> bool {
821 2 * (len1 + len2) < len2 * log2_fast(len1)
824 if better_to_rebuild(self.len(), other.len()) {
825 self.data.append(&mut other.data);
828 self.extend(other.drain());
833 /// Hole represents a hole in a slice i.e. an index without valid value
834 /// (because it was moved from or duplicated).
835 /// In drop, `Hole` will restore the slice by filling the hole
836 /// position with the value that was originally removed.
837 struct Hole<'a, T: 'a> {
839 /// `elt` is always `Some` from new until drop.
844 impl<'a, T> Hole<'a, T> {
845 /// Create a new Hole at index `pos`.
847 /// Unsafe because pos must be within the data slice.
849 unsafe fn new(data: &'a mut [T], pos: usize) -> Self {
850 debug_assert!(pos < data.len());
851 let elt = ptr::read(&data[pos]);
860 fn pos(&self) -> usize {
864 /// Returns a reference to the element removed.
866 fn element(&self) -> &T {
867 self.elt.as_ref().unwrap()
870 /// Returns a reference to the element at `index`.
872 /// Unsafe because index must be within the data slice and not equal to pos.
874 unsafe fn get(&self, index: usize) -> &T {
875 debug_assert!(index != self.pos);
876 debug_assert!(index < self.data.len());
877 self.data.get_unchecked(index)
880 /// Move hole to new location
882 /// Unsafe because index must be within the data slice and not equal to pos.
884 unsafe fn move_to(&mut self, index: usize) {
885 debug_assert!(index != self.pos);
886 debug_assert!(index < self.data.len());
887 let index_ptr: *const _ = self.data.get_unchecked(index);
888 let hole_ptr = self.data.get_unchecked_mut(self.pos);
889 ptr::copy_nonoverlapping(index_ptr, hole_ptr, 1);
894 impl<'a, T> Drop for Hole<'a, T> {
897 // fill the hole again
900 ptr::write(self.data.get_unchecked_mut(pos), self.elt.take().unwrap());
905 /// An iterator over the elements of a `BinaryHeap`.
907 /// This `struct` is created by the [`iter`] method on [`BinaryHeap`]. See its
908 /// documentation for more.
910 /// [`iter`]: struct.BinaryHeap.html#method.iter
911 /// [`BinaryHeap`]: struct.BinaryHeap.html
912 #[stable(feature = "rust1", since = "1.0.0")]
913 pub struct Iter<'a, T: 'a> {
914 iter: slice::Iter<'a, T>,
917 #[stable(feature = "collection_debug", since = "1.17.0")]
918 impl<'a, T: 'a + fmt::Debug> fmt::Debug for Iter<'a, T> {
919 fn fmt(&self, f: &mut fmt::Formatter) -> fmt::Result {
920 f.debug_tuple("Iter")
921 .field(&self.iter.as_slice())
926 // FIXME(#19839) Remove in favor of `#[derive(Clone)]`
927 #[stable(feature = "rust1", since = "1.0.0")]
928 impl<'a, T> Clone for Iter<'a, T> {
929 fn clone(&self) -> Iter<'a, T> {
930 Iter { iter: self.iter.clone() }
934 #[stable(feature = "rust1", since = "1.0.0")]
935 impl<'a, T> Iterator for Iter<'a, T> {
939 fn next(&mut self) -> Option<&'a T> {
944 fn size_hint(&self) -> (usize, Option<usize>) {
945 self.iter.size_hint()
949 #[stable(feature = "rust1", since = "1.0.0")]
950 impl<'a, T> DoubleEndedIterator for Iter<'a, T> {
952 fn next_back(&mut self) -> Option<&'a T> {
953 self.iter.next_back()
957 #[stable(feature = "rust1", since = "1.0.0")]
958 impl<'a, T> ExactSizeIterator for Iter<'a, T> {
959 fn is_empty(&self) -> bool {
964 #[unstable(feature = "fused", issue = "35602")]
965 impl<'a, T> FusedIterator for Iter<'a, T> {}
967 /// An owning iterator over the elements of a `BinaryHeap`.
969 /// This `struct` is created by the [`into_iter`] method on [`BinaryHeap`][`BinaryHeap`]
970 /// (provided by the `IntoIterator` trait). See its documentation for more.
972 /// [`into_iter`]: struct.BinaryHeap.html#method.into_iter
973 /// [`BinaryHeap`]: struct.BinaryHeap.html
974 #[stable(feature = "rust1", since = "1.0.0")]
976 pub struct IntoIter<T> {
977 iter: vec::IntoIter<T>,
980 #[stable(feature = "collection_debug", since = "1.17.0")]
981 impl<T: fmt::Debug> fmt::Debug for IntoIter<T> {
982 fn fmt(&self, f: &mut fmt::Formatter) -> fmt::Result {
983 f.debug_tuple("IntoIter")
984 .field(&self.iter.as_slice())
989 #[stable(feature = "rust1", since = "1.0.0")]
990 impl<T> Iterator for IntoIter<T> {
994 fn next(&mut self) -> Option<T> {
999 fn size_hint(&self) -> (usize, Option<usize>) {
1000 self.iter.size_hint()
1004 #[stable(feature = "rust1", since = "1.0.0")]
1005 impl<T> DoubleEndedIterator for IntoIter<T> {
1007 fn next_back(&mut self) -> Option<T> {
1008 self.iter.next_back()
1012 #[stable(feature = "rust1", since = "1.0.0")]
1013 impl<T> ExactSizeIterator for IntoIter<T> {
1014 fn is_empty(&self) -> bool {
1015 self.iter.is_empty()
1019 #[unstable(feature = "fused", issue = "35602")]
1020 impl<T> FusedIterator for IntoIter<T> {}
1022 /// A draining iterator over the elements of a `BinaryHeap`.
1024 /// This `struct` is created by the [`drain`] method on [`BinaryHeap`]. See its
1025 /// documentation for more.
1027 /// [`drain`]: struct.BinaryHeap.html#method.drain
1028 /// [`BinaryHeap`]: struct.BinaryHeap.html
1029 #[stable(feature = "drain", since = "1.6.0")]
1031 pub struct Drain<'a, T: 'a> {
1032 iter: vec::Drain<'a, T>,
1035 #[stable(feature = "drain", since = "1.6.0")]
1036 impl<'a, T: 'a> Iterator for Drain<'a, T> {
1040 fn next(&mut self) -> Option<T> {
1045 fn size_hint(&self) -> (usize, Option<usize>) {
1046 self.iter.size_hint()
1050 #[stable(feature = "drain", since = "1.6.0")]
1051 impl<'a, T: 'a> DoubleEndedIterator for Drain<'a, T> {
1053 fn next_back(&mut self) -> Option<T> {
1054 self.iter.next_back()
1058 #[stable(feature = "drain", since = "1.6.0")]
1059 impl<'a, T: 'a> ExactSizeIterator for Drain<'a, T> {
1060 fn is_empty(&self) -> bool {
1061 self.iter.is_empty()
1065 #[unstable(feature = "fused", issue = "35602")]
1066 impl<'a, T: 'a> FusedIterator for Drain<'a, T> {}
1068 #[stable(feature = "binary_heap_extras_15", since = "1.5.0")]
1069 impl<T: Ord> From<Vec<T>> for BinaryHeap<T> {
1070 fn from(vec: Vec<T>) -> BinaryHeap<T> {
1071 let mut heap = BinaryHeap { data: vec };
1077 #[stable(feature = "binary_heap_extras_15", since = "1.5.0")]
1078 impl<T> From<BinaryHeap<T>> for Vec<T> {
1079 fn from(heap: BinaryHeap<T>) -> Vec<T> {
1084 #[stable(feature = "rust1", since = "1.0.0")]
1085 impl<T: Ord> FromIterator<T> for BinaryHeap<T> {
1086 fn from_iter<I: IntoIterator<Item = T>>(iter: I) -> BinaryHeap<T> {
1087 BinaryHeap::from(iter.into_iter().collect::<Vec<_>>())
1091 #[stable(feature = "rust1", since = "1.0.0")]
1092 impl<T: Ord> IntoIterator for BinaryHeap<T> {
1094 type IntoIter = IntoIter<T>;
1096 /// Creates a consuming iterator, that is, one that moves each value out of
1097 /// the binary heap in arbitrary order. The binary heap cannot be used
1098 /// after calling this.
1105 /// use std::collections::BinaryHeap;
1106 /// let heap = BinaryHeap::from(vec![1, 2, 3, 4]);
1108 /// // Print 1, 2, 3, 4 in arbitrary order
1109 /// for x in heap.into_iter() {
1110 /// // x has type i32, not &i32
1111 /// println!("{}", x);
1114 fn into_iter(self) -> IntoIter<T> {
1115 IntoIter { iter: self.data.into_iter() }
1119 #[stable(feature = "rust1", since = "1.0.0")]
1120 impl<'a, T> IntoIterator for &'a BinaryHeap<T>
1124 type IntoIter = Iter<'a, T>;
1126 fn into_iter(self) -> Iter<'a, T> {
1131 #[stable(feature = "rust1", since = "1.0.0")]
1132 impl<T: Ord> Extend<T> for BinaryHeap<T> {
1134 fn extend<I: IntoIterator<Item = T>>(&mut self, iter: I) {
1135 <Self as SpecExtend<I>>::spec_extend(self, iter);
1139 impl<T: Ord, I: IntoIterator<Item = T>> SpecExtend<I> for BinaryHeap<T> {
1140 default fn spec_extend(&mut self, iter: I) {
1141 self.extend_desugared(iter.into_iter());
1145 impl<T: Ord> SpecExtend<BinaryHeap<T>> for BinaryHeap<T> {
1146 fn spec_extend(&mut self, ref mut other: BinaryHeap<T>) {
1151 impl<T: Ord> BinaryHeap<T> {
1152 fn extend_desugared<I: IntoIterator<Item = T>>(&mut self, iter: I) {
1153 let iterator = iter.into_iter();
1154 let (lower, _) = iterator.size_hint();
1156 self.reserve(lower);
1158 for elem in iterator {
1164 #[stable(feature = "extend_ref", since = "1.2.0")]
1165 impl<'a, T: 'a + Ord + Copy> Extend<&'a T> for BinaryHeap<T> {
1166 fn extend<I: IntoIterator<Item = &'a T>>(&mut self, iter: I) {
1167 self.extend(iter.into_iter().cloned());
1171 #[unstable(feature = "collection_placement",
1172 reason = "placement protocol is subject to change",
1174 pub struct BinaryHeapPlace<'a, T: 'a>
1175 where T: Clone + Ord {
1176 heap: *mut BinaryHeap<T>,
1177 place: vec::PlaceBack<'a, T>,
1180 #[unstable(feature = "collection_placement",
1181 reason = "placement protocol is subject to change",
1183 impl<'a, T: Clone + Ord + fmt::Debug> fmt::Debug for BinaryHeapPlace<'a, T> {
1184 fn fmt(&self, f: &mut fmt::Formatter) -> fmt::Result {
1185 f.debug_tuple("BinaryHeapPlace")
1191 #[unstable(feature = "collection_placement",
1192 reason = "placement protocol is subject to change",
1194 impl<'a, T: 'a> Placer<T> for &'a mut BinaryHeap<T>
1195 where T: Clone + Ord {
1196 type Place = BinaryHeapPlace<'a, T>;
1198 fn make_place(self) -> Self::Place {
1199 let ptr = self as *mut BinaryHeap<T>;
1200 let place = Placer::make_place(self.data.place_back());
1208 #[unstable(feature = "collection_placement",
1209 reason = "placement protocol is subject to change",
1211 impl<'a, T> Place<T> for BinaryHeapPlace<'a, T>
1212 where T: Clone + Ord {
1213 fn pointer(&mut self) -> *mut T {
1214 self.place.pointer()
1218 #[unstable(feature = "collection_placement",
1219 reason = "placement protocol is subject to change",
1221 impl<'a, T> InPlace<T> for BinaryHeapPlace<'a, T>
1222 where T: Clone + Ord {
1225 unsafe fn finalize(self) -> &'a T {
1226 self.place.finalize();
1228 let heap: &mut BinaryHeap<T> = &mut *self.heap;
1229 let len = heap.len();
1230 let i = heap.sift_up(0, len - 1);
1231 heap.data.get_unchecked(i)