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, Place, Placer, InPlace};
159 use core::iter::{FromIterator, FusedIterator};
160 use core::mem::{swap, size_of};
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 /// Removes the greatest item from the binary heap and returns it, or `None` if it
520 /// use std::collections::BinaryHeap;
521 /// let mut heap = BinaryHeap::from(vec![1, 3]);
523 /// assert_eq!(heap.pop(), Some(3));
524 /// assert_eq!(heap.pop(), Some(1));
525 /// assert_eq!(heap.pop(), None);
527 #[stable(feature = "rust1", since = "1.0.0")]
528 pub fn pop(&mut self) -> Option<T> {
529 self.data.pop().map(|mut item| {
530 if !self.is_empty() {
531 swap(&mut item, &mut self.data[0]);
532 self.sift_down_to_bottom(0);
538 /// Pushes an item onto the binary heap.
545 /// use std::collections::BinaryHeap;
546 /// let mut heap = BinaryHeap::new();
551 /// assert_eq!(heap.len(), 3);
552 /// assert_eq!(heap.peek(), Some(&5));
554 #[stable(feature = "rust1", since = "1.0.0")]
555 pub fn push(&mut self, item: T) {
556 let old_len = self.len();
557 self.data.push(item);
558 self.sift_up(0, old_len);
561 /// Consumes the `BinaryHeap` and returns the underlying vector
562 /// in arbitrary order.
569 /// use std::collections::BinaryHeap;
570 /// let heap = BinaryHeap::from(vec![1, 2, 3, 4, 5, 6, 7]);
571 /// let vec = heap.into_vec();
573 /// // Will print in some order
575 /// println!("{}", x);
578 #[stable(feature = "binary_heap_extras_15", since = "1.5.0")]
579 pub fn into_vec(self) -> Vec<T> {
583 /// Consumes the `BinaryHeap` and returns a vector in sorted
584 /// (ascending) order.
591 /// use std::collections::BinaryHeap;
593 /// let mut heap = BinaryHeap::from(vec![1, 2, 4, 5, 7]);
597 /// let vec = heap.into_sorted_vec();
598 /// assert_eq!(vec, [1, 2, 3, 4, 5, 6, 7]);
600 #[stable(feature = "binary_heap_extras_15", since = "1.5.0")]
601 pub fn into_sorted_vec(mut self) -> Vec<T> {
602 let mut end = self.len();
605 self.data.swap(0, end);
606 self.sift_down_range(0, end);
611 // The implementations of sift_up and sift_down use unsafe blocks in
612 // order to move an element out of the vector (leaving behind a
613 // hole), shift along the others and move the removed element back into the
614 // vector at the final location of the hole.
615 // The `Hole` type is used to represent this, and make sure
616 // the hole is filled back at the end of its scope, even on panic.
617 // Using a hole reduces the constant factor compared to using swaps,
618 // which involves twice as many moves.
619 fn sift_up(&mut self, start: usize, pos: usize) -> usize {
621 // Take out the value at `pos` and create a hole.
622 let mut hole = Hole::new(&mut self.data, pos);
624 while hole.pos() > start {
625 let parent = (hole.pos() - 1) / 2;
626 if hole.element() <= hole.get(parent) {
629 hole.move_to(parent);
635 /// Take an element at `pos` and move it down the heap,
636 /// while its children are larger.
637 fn sift_down_range(&mut self, pos: usize, end: usize) {
639 let mut hole = Hole::new(&mut self.data, pos);
640 let mut child = 2 * pos + 1;
642 let right = child + 1;
643 // compare with the greater of the two children
644 if right < end && !(hole.get(child) > hole.get(right)) {
647 // if we are already in order, stop.
648 if hole.element() >= hole.get(child) {
652 child = 2 * hole.pos() + 1;
657 fn sift_down(&mut self, pos: usize) {
658 let len = self.len();
659 self.sift_down_range(pos, len);
662 /// Take an element at `pos` and move it all the way down the heap,
663 /// then sift it up to its position.
665 /// Note: This is faster when the element is known to be large / should
666 /// be closer to the bottom.
667 fn sift_down_to_bottom(&mut self, mut pos: usize) {
668 let end = self.len();
671 let mut hole = Hole::new(&mut self.data, pos);
672 let mut child = 2 * pos + 1;
674 let right = child + 1;
675 // compare with the greater of the two children
676 if right < end && !(hole.get(child) > hole.get(right)) {
680 child = 2 * hole.pos() + 1;
684 self.sift_up(start, pos);
687 /// Returns the length of the binary heap.
694 /// use std::collections::BinaryHeap;
695 /// let heap = BinaryHeap::from(vec![1, 3]);
697 /// assert_eq!(heap.len(), 2);
699 #[stable(feature = "rust1", since = "1.0.0")]
700 pub fn len(&self) -> usize {
704 /// Checks if the binary heap is empty.
711 /// use std::collections::BinaryHeap;
712 /// let mut heap = BinaryHeap::new();
714 /// assert!(heap.is_empty());
720 /// assert!(!heap.is_empty());
722 #[stable(feature = "rust1", since = "1.0.0")]
723 pub fn is_empty(&self) -> bool {
727 /// Clears the binary heap, returning an iterator over the removed elements.
729 /// The elements are removed in arbitrary order.
736 /// use std::collections::BinaryHeap;
737 /// let mut heap = BinaryHeap::from(vec![1, 3]);
739 /// assert!(!heap.is_empty());
741 /// for x in heap.drain() {
742 /// println!("{}", x);
745 /// assert!(heap.is_empty());
748 #[stable(feature = "drain", since = "1.6.0")]
749 pub fn drain(&mut self) -> Drain<T> {
750 Drain { iter: self.data.drain(..) }
753 /// Drops all items from the binary heap.
760 /// use std::collections::BinaryHeap;
761 /// let mut heap = BinaryHeap::from(vec![1, 3]);
763 /// assert!(!heap.is_empty());
767 /// assert!(heap.is_empty());
769 #[stable(feature = "rust1", since = "1.0.0")]
770 pub fn clear(&mut self) {
774 fn rebuild(&mut self) {
775 let mut n = self.len() / 2;
782 /// Moves all the elements of `other` into `self`, leaving `other` empty.
789 /// use std::collections::BinaryHeap;
791 /// let v = vec![-10, 1, 2, 3, 3];
792 /// let mut a = BinaryHeap::from(v);
794 /// let v = vec![-20, 5, 43];
795 /// let mut b = BinaryHeap::from(v);
797 /// a.append(&mut b);
799 /// assert_eq!(a.into_sorted_vec(), [-20, -10, 1, 2, 3, 3, 5, 43]);
800 /// assert!(b.is_empty());
802 #[stable(feature = "binary_heap_append", since = "1.11.0")]
803 pub fn append(&mut self, other: &mut Self) {
804 if self.len() < other.len() {
808 if other.is_empty() {
813 fn log2_fast(x: usize) -> usize {
814 8 * size_of::<usize>() - (x.leading_zeros() as usize) - 1
817 // `rebuild` takes O(len1 + len2) operations
818 // and about 2 * (len1 + len2) comparisons in the worst case
819 // while `extend` takes O(len2 * log_2(len1)) operations
820 // and about 1 * len2 * log_2(len1) comparisons in the worst case,
821 // assuming len1 >= len2.
823 fn better_to_rebuild(len1: usize, len2: usize) -> bool {
824 2 * (len1 + len2) < len2 * log2_fast(len1)
827 if better_to_rebuild(self.len(), other.len()) {
828 self.data.append(&mut other.data);
831 self.extend(other.drain());
836 /// Hole represents a hole in a slice i.e. an index without valid value
837 /// (because it was moved from or duplicated).
838 /// In drop, `Hole` will restore the slice by filling the hole
839 /// position with the value that was originally removed.
840 struct Hole<'a, T: 'a> {
842 /// `elt` is always `Some` from new until drop.
847 impl<'a, T> Hole<'a, T> {
848 /// Create a new Hole at index `pos`.
850 /// Unsafe because pos must be within the data slice.
852 unsafe fn new(data: &'a mut [T], pos: usize) -> Self {
853 debug_assert!(pos < data.len());
854 let elt = ptr::read(&data[pos]);
863 fn pos(&self) -> usize {
867 /// Returns a reference to the element removed.
869 fn element(&self) -> &T {
870 self.elt.as_ref().unwrap()
873 /// Returns a reference to the element at `index`.
875 /// Unsafe because index must be within the data slice and not equal to pos.
877 unsafe fn get(&self, index: usize) -> &T {
878 debug_assert!(index != self.pos);
879 debug_assert!(index < self.data.len());
880 self.data.get_unchecked(index)
883 /// Move hole to new location
885 /// Unsafe because index must be within the data slice and not equal to pos.
887 unsafe fn move_to(&mut self, index: usize) {
888 debug_assert!(index != self.pos);
889 debug_assert!(index < self.data.len());
890 let index_ptr: *const _ = self.data.get_unchecked(index);
891 let hole_ptr = self.data.get_unchecked_mut(self.pos);
892 ptr::copy_nonoverlapping(index_ptr, hole_ptr, 1);
897 impl<'a, T> Drop for Hole<'a, T> {
900 // fill the hole again
903 ptr::write(self.data.get_unchecked_mut(pos), self.elt.take().unwrap());
908 /// An iterator over the elements of a `BinaryHeap`.
910 /// This `struct` is created by the [`iter`] method on [`BinaryHeap`]. See its
911 /// documentation for more.
913 /// [`iter`]: struct.BinaryHeap.html#method.iter
914 /// [`BinaryHeap`]: struct.BinaryHeap.html
915 #[stable(feature = "rust1", since = "1.0.0")]
916 pub struct Iter<'a, T: 'a> {
917 iter: slice::Iter<'a, T>,
920 #[stable(feature = "collection_debug", since = "1.17.0")]
921 impl<'a, T: 'a + fmt::Debug> fmt::Debug for Iter<'a, T> {
922 fn fmt(&self, f: &mut fmt::Formatter) -> fmt::Result {
923 f.debug_tuple("Iter")
924 .field(&self.iter.as_slice())
929 // FIXME(#26925) Remove in favor of `#[derive(Clone)]`
930 #[stable(feature = "rust1", since = "1.0.0")]
931 impl<'a, T> Clone for Iter<'a, T> {
932 fn clone(&self) -> Iter<'a, T> {
933 Iter { iter: self.iter.clone() }
937 #[stable(feature = "rust1", since = "1.0.0")]
938 impl<'a, T> Iterator for Iter<'a, T> {
942 fn next(&mut self) -> Option<&'a T> {
947 fn size_hint(&self) -> (usize, Option<usize>) {
948 self.iter.size_hint()
952 #[stable(feature = "rust1", since = "1.0.0")]
953 impl<'a, T> DoubleEndedIterator for Iter<'a, T> {
955 fn next_back(&mut self) -> Option<&'a T> {
956 self.iter.next_back()
960 #[stable(feature = "rust1", since = "1.0.0")]
961 impl<'a, T> ExactSizeIterator for Iter<'a, T> {
962 fn is_empty(&self) -> bool {
967 #[stable(feature = "fused", since = "1.26.0")]
968 impl<'a, T> FusedIterator for Iter<'a, T> {}
970 /// An owning iterator over the elements of a `BinaryHeap`.
972 /// This `struct` is created by the [`into_iter`] method on [`BinaryHeap`][`BinaryHeap`]
973 /// (provided by the `IntoIterator` trait). See its documentation for more.
975 /// [`into_iter`]: struct.BinaryHeap.html#method.into_iter
976 /// [`BinaryHeap`]: struct.BinaryHeap.html
977 #[stable(feature = "rust1", since = "1.0.0")]
979 pub struct IntoIter<T> {
980 iter: vec::IntoIter<T>,
983 #[stable(feature = "collection_debug", since = "1.17.0")]
984 impl<T: fmt::Debug> fmt::Debug for IntoIter<T> {
985 fn fmt(&self, f: &mut fmt::Formatter) -> fmt::Result {
986 f.debug_tuple("IntoIter")
987 .field(&self.iter.as_slice())
992 #[stable(feature = "rust1", since = "1.0.0")]
993 impl<T> Iterator for IntoIter<T> {
997 fn next(&mut self) -> Option<T> {
1002 fn size_hint(&self) -> (usize, Option<usize>) {
1003 self.iter.size_hint()
1007 #[stable(feature = "rust1", since = "1.0.0")]
1008 impl<T> DoubleEndedIterator for IntoIter<T> {
1010 fn next_back(&mut self) -> Option<T> {
1011 self.iter.next_back()
1015 #[stable(feature = "rust1", since = "1.0.0")]
1016 impl<T> ExactSizeIterator for IntoIter<T> {
1017 fn is_empty(&self) -> bool {
1018 self.iter.is_empty()
1022 #[stable(feature = "fused", since = "1.26.0")]
1023 impl<T> FusedIterator for IntoIter<T> {}
1025 /// A draining iterator over the elements of a `BinaryHeap`.
1027 /// This `struct` is created by the [`drain`] method on [`BinaryHeap`]. See its
1028 /// documentation for more.
1030 /// [`drain`]: struct.BinaryHeap.html#method.drain
1031 /// [`BinaryHeap`]: struct.BinaryHeap.html
1032 #[stable(feature = "drain", since = "1.6.0")]
1034 pub struct Drain<'a, T: 'a> {
1035 iter: vec::Drain<'a, T>,
1038 #[stable(feature = "drain", since = "1.6.0")]
1039 impl<'a, T: 'a> Iterator for Drain<'a, T> {
1043 fn next(&mut self) -> Option<T> {
1048 fn size_hint(&self) -> (usize, Option<usize>) {
1049 self.iter.size_hint()
1053 #[stable(feature = "drain", since = "1.6.0")]
1054 impl<'a, T: 'a> DoubleEndedIterator for Drain<'a, T> {
1056 fn next_back(&mut self) -> Option<T> {
1057 self.iter.next_back()
1061 #[stable(feature = "drain", since = "1.6.0")]
1062 impl<'a, T: 'a> ExactSizeIterator for Drain<'a, T> {
1063 fn is_empty(&self) -> bool {
1064 self.iter.is_empty()
1068 #[stable(feature = "fused", since = "1.26.0")]
1069 impl<'a, T: 'a> FusedIterator for Drain<'a, T> {}
1071 #[stable(feature = "binary_heap_extras_15", since = "1.5.0")]
1072 impl<T: Ord> From<Vec<T>> for BinaryHeap<T> {
1073 fn from(vec: Vec<T>) -> BinaryHeap<T> {
1074 let mut heap = BinaryHeap { data: vec };
1080 #[stable(feature = "binary_heap_extras_15", since = "1.5.0")]
1081 impl<T> From<BinaryHeap<T>> for Vec<T> {
1082 fn from(heap: BinaryHeap<T>) -> Vec<T> {
1087 #[stable(feature = "rust1", since = "1.0.0")]
1088 impl<T: Ord> FromIterator<T> for BinaryHeap<T> {
1089 fn from_iter<I: IntoIterator<Item = T>>(iter: I) -> BinaryHeap<T> {
1090 BinaryHeap::from(iter.into_iter().collect::<Vec<_>>())
1094 #[stable(feature = "rust1", since = "1.0.0")]
1095 impl<T: Ord> IntoIterator for BinaryHeap<T> {
1097 type IntoIter = IntoIter<T>;
1099 /// Creates a consuming iterator, that is, one that moves each value out of
1100 /// the binary heap in arbitrary order. The binary heap cannot be used
1101 /// after calling this.
1108 /// use std::collections::BinaryHeap;
1109 /// let heap = BinaryHeap::from(vec![1, 2, 3, 4]);
1111 /// // Print 1, 2, 3, 4 in arbitrary order
1112 /// for x in heap.into_iter() {
1113 /// // x has type i32, not &i32
1114 /// println!("{}", x);
1117 fn into_iter(self) -> IntoIter<T> {
1118 IntoIter { iter: self.data.into_iter() }
1122 #[stable(feature = "rust1", since = "1.0.0")]
1123 impl<'a, T> IntoIterator for &'a BinaryHeap<T>
1127 type IntoIter = Iter<'a, T>;
1129 fn into_iter(self) -> Iter<'a, T> {
1134 #[stable(feature = "rust1", since = "1.0.0")]
1135 impl<T: Ord> Extend<T> for BinaryHeap<T> {
1137 fn extend<I: IntoIterator<Item = T>>(&mut self, iter: I) {
1138 <Self as SpecExtend<I>>::spec_extend(self, iter);
1142 impl<T: Ord, I: IntoIterator<Item = T>> SpecExtend<I> for BinaryHeap<T> {
1143 default fn spec_extend(&mut self, iter: I) {
1144 self.extend_desugared(iter.into_iter());
1148 impl<T: Ord> SpecExtend<BinaryHeap<T>> for BinaryHeap<T> {
1149 fn spec_extend(&mut self, ref mut other: BinaryHeap<T>) {
1154 impl<T: Ord> BinaryHeap<T> {
1155 fn extend_desugared<I: IntoIterator<Item = T>>(&mut self, iter: I) {
1156 let iterator = iter.into_iter();
1157 let (lower, _) = iterator.size_hint();
1159 self.reserve(lower);
1161 for elem in iterator {
1167 #[stable(feature = "extend_ref", since = "1.2.0")]
1168 impl<'a, T: 'a + Ord + Copy> Extend<&'a T> for BinaryHeap<T> {
1169 fn extend<I: IntoIterator<Item = &'a T>>(&mut self, iter: I) {
1170 self.extend(iter.into_iter().cloned());
1174 #[unstable(feature = "collection_placement",
1175 reason = "placement protocol is subject to change",
1177 pub struct BinaryHeapPlace<'a, T: 'a>
1178 where T: Clone + Ord {
1179 heap: *mut BinaryHeap<T>,
1180 place: vec::PlaceBack<'a, T>,
1183 #[unstable(feature = "collection_placement",
1184 reason = "placement protocol is subject to change",
1186 impl<'a, T: Clone + Ord + fmt::Debug> fmt::Debug for BinaryHeapPlace<'a, T> {
1187 fn fmt(&self, f: &mut fmt::Formatter) -> fmt::Result {
1188 f.debug_tuple("BinaryHeapPlace")
1194 #[unstable(feature = "collection_placement",
1195 reason = "placement protocol is subject to change",
1197 impl<'a, T: 'a> Placer<T> for &'a mut BinaryHeap<T>
1198 where T: Clone + Ord {
1199 type Place = BinaryHeapPlace<'a, T>;
1201 fn make_place(self) -> Self::Place {
1202 let ptr = self as *mut BinaryHeap<T>;
1203 let place = Placer::make_place(self.data.place_back());
1211 #[unstable(feature = "collection_placement",
1212 reason = "placement protocol is subject to change",
1214 unsafe impl<'a, T> Place<T> for BinaryHeapPlace<'a, T>
1215 where T: Clone + Ord {
1216 fn pointer(&mut self) -> *mut T {
1217 self.place.pointer()
1221 #[unstable(feature = "collection_placement",
1222 reason = "placement protocol is subject to change",
1224 impl<'a, T> InPlace<T> for BinaryHeapPlace<'a, T>
1225 where T: Clone + Ord {
1228 unsafe fn finalize(self) -> &'a T {
1229 self.place.finalize();
1231 let heap: &mut BinaryHeap<T> = &mut *self.heap;
1232 let len = heap.len();
1233 let i = heap.sift_up(0, len - 1);
1234 heap.data.get_unchecked(i)