]> git.proxmox.com Git - rustc.git/blob - src/libcollections/binary_heap.rs
Imported Upstream version 1.0.0~beta.3
[rustc.git] / src / libcollections / binary_heap.rs
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.
4 //
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.
10
11 //! A priority queue implemented with a binary heap.
12 //!
13 //! Insertion and popping the largest element have `O(log n)` time complexity. Checking the largest
14 //! element is `O(1)`. Converting a vector to a binary heap can be done in-place, and has `O(n)`
15 //! complexity. A binary heap can also be converted to a sorted vector in-place, allowing it to
16 //! be used for an `O(n log n)` in-place heapsort.
17 //!
18 //! # Examples
19 //!
20 //! This is a larger example that implements [Dijkstra's algorithm][dijkstra]
21 //! to solve the [shortest path problem][sssp] on a [directed graph][dir_graph].
22 //! It shows how to use `BinaryHeap` with custom types.
23 //!
24 //! [dijkstra]: http://en.wikipedia.org/wiki/Dijkstra%27s_algorithm
25 //! [sssp]: http://en.wikipedia.org/wiki/Shortest_path_problem
26 //! [dir_graph]: http://en.wikipedia.org/wiki/Directed_graph
27 //!
28 //! ```
29 //! use std::cmp::Ordering;
30 //! use std::collections::BinaryHeap;
31 //! use std::usize;
32 //!
33 //! #[derive(Copy, Clone, Eq, PartialEq)]
34 //! struct State {
35 //! cost: usize,
36 //! position: usize,
37 //! }
38 //!
39 //! // The priority queue depends on `Ord`.
40 //! // Explicitly implement the trait so the queue becomes a min-heap
41 //! // instead of a max-heap.
42 //! impl Ord for State {
43 //! fn cmp(&self, other: &State) -> Ordering {
44 //! // Notice that the we flip the ordering here
45 //! other.cost.cmp(&self.cost)
46 //! }
47 //! }
48 //!
49 //! // `PartialOrd` needs to be implemented as well.
50 //! impl PartialOrd for State {
51 //! fn partial_cmp(&self, other: &State) -> Option<Ordering> {
52 //! Some(self.cmp(other))
53 //! }
54 //! }
55 //!
56 //! // Each node is represented as an `usize`, for a shorter implementation.
57 //! struct Edge {
58 //! node: usize,
59 //! cost: usize,
60 //! }
61 //!
62 //! // Dijkstra's shortest path algorithm.
63 //!
64 //! // Start at `start` and use `dist` to track the current shortest distance
65 //! // to each node. This implementation isn't memory-efficient as it may leave duplicate
66 //! // nodes in the queue. It also uses `usize::MAX` as a sentinel value,
67 //! // for a simpler implementation.
68 //! fn shortest_path(adj_list: &Vec<Vec<Edge>>, start: usize, goal: usize) -> usize {
69 //! // dist[node] = current shortest distance from `start` to `node`
70 //! let mut dist: Vec<_> = (0..adj_list.len()).map(|_| usize::MAX).collect();
71 //!
72 //! let mut heap = BinaryHeap::new();
73 //!
74 //! // We're at `start`, with a zero cost
75 //! dist[start] = 0;
76 //! heap.push(State { cost: 0, position: start });
77 //!
78 //! // Examine the frontier with lower cost nodes first (min-heap)
79 //! while let Some(State { cost, position }) = heap.pop() {
80 //! // Alternatively we could have continued to find all shortest paths
81 //! if position == goal { return cost; }
82 //!
83 //! // Important as we may have already found a better way
84 //! if cost > dist[position] { continue; }
85 //!
86 //! // For each node we can reach, see if we can find a way with
87 //! // a lower cost going through this node
88 //! for edge in adj_list[position].iter() {
89 //! let next = State { cost: cost + edge.cost, position: edge.node };
90 //!
91 //! // If so, add it to the frontier and continue
92 //! if next.cost < dist[next.position] {
93 //! heap.push(next);
94 //! // Relaxation, we have now found a better way
95 //! dist[next.position] = next.cost;
96 //! }
97 //! }
98 //! }
99 //!
100 //! // Goal not reachable
101 //! usize::MAX
102 //! }
103 //!
104 //! fn main() {
105 //! // This is the directed graph we're going to use.
106 //! // The node numbers correspond to the different states,
107 //! // and the edge weights symbolize the cost of moving
108 //! // from one node to another.
109 //! // Note that the edges are one-way.
110 //! //
111 //! // 7
112 //! // +-----------------+
113 //! // | |
114 //! // v 1 2 |
115 //! // 0 -----> 1 -----> 3 ---> 4
116 //! // | ^ ^ ^
117 //! // | | 1 | |
118 //! // | | | 3 | 1
119 //! // +------> 2 -------+ |
120 //! // 10 | |
121 //! // +---------------+
122 //! //
123 //! // The graph is represented as an adjacency list where each index,
124 //! // corresponding to a node value, has a list of outgoing edges.
125 //! // Chosen for its efficiency.
126 //! let graph = vec![
127 //! // Node 0
128 //! vec![Edge { node: 2, cost: 10 },
129 //! Edge { node: 1, cost: 1 }],
130 //! // Node 1
131 //! vec![Edge { node: 3, cost: 2 }],
132 //! // Node 2
133 //! vec![Edge { node: 1, cost: 1 },
134 //! Edge { node: 3, cost: 3 },
135 //! Edge { node: 4, cost: 1 }],
136 //! // Node 3
137 //! vec![Edge { node: 0, cost: 7 },
138 //! Edge { node: 4, cost: 2 }],
139 //! // Node 4
140 //! vec![]];
141 //!
142 //! assert_eq!(shortest_path(&graph, 0, 1), 1);
143 //! assert_eq!(shortest_path(&graph, 0, 3), 3);
144 //! assert_eq!(shortest_path(&graph, 3, 0), 7);
145 //! assert_eq!(shortest_path(&graph, 0, 4), 5);
146 //! assert_eq!(shortest_path(&graph, 4, 0), usize::MAX);
147 //! }
148 //! ```
149
150 #![allow(missing_docs)]
151 #![stable(feature = "rust1", since = "1.0.0")]
152
153 use core::prelude::*;
154
155 use core::iter::{FromIterator};
156 use core::mem::{zeroed, replace, swap};
157 use core::ptr;
158
159 use slice;
160 use vec::{self, Vec};
161
162 /// A priority queue implemented with a binary heap.
163 ///
164 /// This will be a max-heap.
165 ///
166 /// It is a logic error for an item to be modified in such a way that the
167 /// item's ordering relative to any other item, as determined by the `Ord`
168 /// trait, changes while it is in the heap. This is normally only possible
169 /// through `Cell`, `RefCell`, global state, I/O, or unsafe code.
170 #[derive(Clone)]
171 #[stable(feature = "rust1", since = "1.0.0")]
172 pub struct BinaryHeap<T> {
173 data: Vec<T>,
174 }
175
176 #[stable(feature = "rust1", since = "1.0.0")]
177 impl<T: Ord> Default for BinaryHeap<T> {
178 #[inline]
179 fn default() -> BinaryHeap<T> { BinaryHeap::new() }
180 }
181
182 impl<T: Ord> BinaryHeap<T> {
183 /// Creates an empty `BinaryHeap` as a max-heap.
184 ///
185 /// # Examples
186 ///
187 /// ```
188 /// use std::collections::BinaryHeap;
189 /// let mut heap = BinaryHeap::new();
190 /// heap.push(4);
191 /// ```
192 #[stable(feature = "rust1", since = "1.0.0")]
193 pub fn new() -> BinaryHeap<T> { BinaryHeap { data: vec![] } }
194
195 /// Creates an empty `BinaryHeap` with a specific capacity.
196 /// This preallocates enough memory for `capacity` elements,
197 /// so that the `BinaryHeap` does not have to be reallocated
198 /// until it contains at least that many values.
199 ///
200 /// # Examples
201 ///
202 /// ```
203 /// use std::collections::BinaryHeap;
204 /// let mut heap = BinaryHeap::with_capacity(10);
205 /// heap.push(4);
206 /// ```
207 #[stable(feature = "rust1", since = "1.0.0")]
208 pub fn with_capacity(capacity: usize) -> BinaryHeap<T> {
209 BinaryHeap { data: Vec::with_capacity(capacity) }
210 }
211
212 /// Creates a `BinaryHeap` from a vector. This is sometimes called
213 /// `heapifying` the vector.
214 ///
215 /// # Examples
216 ///
217 /// ```
218 /// # #![feature(collections)]
219 /// use std::collections::BinaryHeap;
220 /// let heap = BinaryHeap::from_vec(vec![9, 1, 2, 7, 3, 2]);
221 /// ```
222 pub fn from_vec(vec: Vec<T>) -> BinaryHeap<T> {
223 let mut heap = BinaryHeap { data: vec };
224 let mut n = heap.len() / 2;
225 while n > 0 {
226 n -= 1;
227 heap.sift_down(n);
228 }
229 heap
230 }
231
232 /// Returns an iterator visiting all values in the underlying vector, in
233 /// arbitrary order.
234 ///
235 /// # Examples
236 ///
237 /// ```
238 /// # #![feature(collections)]
239 /// use std::collections::BinaryHeap;
240 /// let heap = BinaryHeap::from_vec(vec![1, 2, 3, 4]);
241 ///
242 /// // Print 1, 2, 3, 4 in arbitrary order
243 /// for x in heap.iter() {
244 /// println!("{}", x);
245 /// }
246 /// ```
247 #[stable(feature = "rust1", since = "1.0.0")]
248 pub fn iter(&self) -> Iter<T> {
249 Iter { iter: self.data.iter() }
250 }
251
252 /// Returns the greatest item in the binary heap, or `None` if it is empty.
253 ///
254 /// # Examples
255 ///
256 /// ```
257 /// use std::collections::BinaryHeap;
258 /// let mut heap = BinaryHeap::new();
259 /// assert_eq!(heap.peek(), None);
260 ///
261 /// heap.push(1);
262 /// heap.push(5);
263 /// heap.push(2);
264 /// assert_eq!(heap.peek(), Some(&5));
265 ///
266 /// ```
267 #[stable(feature = "rust1", since = "1.0.0")]
268 pub fn peek(&self) -> Option<&T> {
269 self.data.get(0)
270 }
271
272 /// Returns the number of elements the binary heap can hold without reallocating.
273 ///
274 /// # Examples
275 ///
276 /// ```
277 /// use std::collections::BinaryHeap;
278 /// let mut heap = BinaryHeap::with_capacity(100);
279 /// assert!(heap.capacity() >= 100);
280 /// heap.push(4);
281 /// ```
282 #[stable(feature = "rust1", since = "1.0.0")]
283 pub fn capacity(&self) -> usize { self.data.capacity() }
284
285 /// Reserves the minimum capacity for exactly `additional` more elements to be inserted in the
286 /// given `BinaryHeap`. Does nothing if the capacity is already sufficient.
287 ///
288 /// Note that the allocator may give the collection more space than it requests. Therefore
289 /// capacity can not be relied upon to be precisely minimal. Prefer `reserve` if future
290 /// insertions are expected.
291 ///
292 /// # Panics
293 ///
294 /// Panics if the new capacity overflows `usize`.
295 ///
296 /// # Examples
297 ///
298 /// ```
299 /// use std::collections::BinaryHeap;
300 /// let mut heap = BinaryHeap::new();
301 /// heap.reserve_exact(100);
302 /// assert!(heap.capacity() >= 100);
303 /// heap.push(4);
304 /// ```
305 #[stable(feature = "rust1", since = "1.0.0")]
306 pub fn reserve_exact(&mut self, additional: usize) {
307 self.data.reserve_exact(additional);
308 }
309
310 /// Reserves capacity for at least `additional` more elements to be inserted in the
311 /// `BinaryHeap`. The collection may reserve more space to avoid frequent reallocations.
312 ///
313 /// # Panics
314 ///
315 /// Panics if the new capacity overflows `usize`.
316 ///
317 /// # Examples
318 ///
319 /// ```
320 /// use std::collections::BinaryHeap;
321 /// let mut heap = BinaryHeap::new();
322 /// heap.reserve(100);
323 /// assert!(heap.capacity() >= 100);
324 /// heap.push(4);
325 /// ```
326 #[stable(feature = "rust1", since = "1.0.0")]
327 pub fn reserve(&mut self, additional: usize) {
328 self.data.reserve(additional);
329 }
330
331 /// Discards as much additional capacity as possible.
332 #[stable(feature = "rust1", since = "1.0.0")]
333 pub fn shrink_to_fit(&mut self) {
334 self.data.shrink_to_fit();
335 }
336
337 /// Removes the greatest item from the binary heap and returns it, or `None` if it
338 /// is empty.
339 ///
340 /// # Examples
341 ///
342 /// ```
343 /// # #![feature(collections)]
344 /// use std::collections::BinaryHeap;
345 /// let mut heap = BinaryHeap::from_vec(vec![1, 3]);
346 ///
347 /// assert_eq!(heap.pop(), Some(3));
348 /// assert_eq!(heap.pop(), Some(1));
349 /// assert_eq!(heap.pop(), None);
350 /// ```
351 #[stable(feature = "rust1", since = "1.0.0")]
352 pub fn pop(&mut self) -> Option<T> {
353 self.data.pop().map(|mut item| {
354 if !self.is_empty() {
355 swap(&mut item, &mut self.data[0]);
356 self.sift_down(0);
357 }
358 item
359 })
360 }
361
362 /// Pushes an item onto the binary heap.
363 ///
364 /// # Examples
365 ///
366 /// ```
367 /// use std::collections::BinaryHeap;
368 /// let mut heap = BinaryHeap::new();
369 /// heap.push(3);
370 /// heap.push(5);
371 /// heap.push(1);
372 ///
373 /// assert_eq!(heap.len(), 3);
374 /// assert_eq!(heap.peek(), Some(&5));
375 /// ```
376 #[stable(feature = "rust1", since = "1.0.0")]
377 pub fn push(&mut self, item: T) {
378 let old_len = self.len();
379 self.data.push(item);
380 self.sift_up(0, old_len);
381 }
382
383 /// Pushes an item onto the binary heap, then pops the greatest item off the queue in
384 /// an optimized fashion.
385 ///
386 /// # Examples
387 ///
388 /// ```
389 /// # #![feature(collections)]
390 /// use std::collections::BinaryHeap;
391 /// let mut heap = BinaryHeap::new();
392 /// heap.push(1);
393 /// heap.push(5);
394 ///
395 /// assert_eq!(heap.push_pop(3), 5);
396 /// assert_eq!(heap.push_pop(9), 9);
397 /// assert_eq!(heap.len(), 2);
398 /// assert_eq!(heap.peek(), Some(&3));
399 /// ```
400 pub fn push_pop(&mut self, mut item: T) -> T {
401 match self.data.get_mut(0) {
402 None => return item,
403 Some(top) => if *top > item {
404 swap(&mut item, top);
405 } else {
406 return item;
407 },
408 }
409
410 self.sift_down(0);
411 item
412 }
413
414 /// Pops the greatest item off the binary heap, then pushes an item onto the queue in
415 /// an optimized fashion. The push is done regardless of whether the binary heap
416 /// was empty.
417 ///
418 /// # Examples
419 ///
420 /// ```
421 /// # #![feature(collections)]
422 /// use std::collections::BinaryHeap;
423 /// let mut heap = BinaryHeap::new();
424 ///
425 /// assert_eq!(heap.replace(1), None);
426 /// assert_eq!(heap.replace(3), Some(1));
427 /// assert_eq!(heap.len(), 1);
428 /// assert_eq!(heap.peek(), Some(&3));
429 /// ```
430 pub fn replace(&mut self, mut item: T) -> Option<T> {
431 if !self.is_empty() {
432 swap(&mut item, &mut self.data[0]);
433 self.sift_down(0);
434 Some(item)
435 } else {
436 self.push(item);
437 None
438 }
439 }
440
441 /// Consumes the `BinaryHeap` and returns the underlying vector
442 /// in arbitrary order.
443 ///
444 /// # Examples
445 ///
446 /// ```
447 /// # #![feature(collections)]
448 /// use std::collections::BinaryHeap;
449 /// let heap = BinaryHeap::from_vec(vec![1, 2, 3, 4, 5, 6, 7]);
450 /// let vec = heap.into_vec();
451 ///
452 /// // Will print in some order
453 /// for x in vec.iter() {
454 /// println!("{}", x);
455 /// }
456 /// ```
457 pub fn into_vec(self) -> Vec<T> { self.data }
458
459 /// Consumes the `BinaryHeap` and returns a vector in sorted
460 /// (ascending) order.
461 ///
462 /// # Examples
463 ///
464 /// ```
465 /// # #![feature(collections)]
466 /// use std::collections::BinaryHeap;
467 ///
468 /// let mut heap = BinaryHeap::from_vec(vec![1, 2, 4, 5, 7]);
469 /// heap.push(6);
470 /// heap.push(3);
471 ///
472 /// let vec = heap.into_sorted_vec();
473 /// assert_eq!(vec, [1, 2, 3, 4, 5, 6, 7]);
474 /// ```
475 pub fn into_sorted_vec(mut self) -> Vec<T> {
476 let mut end = self.len();
477 while end > 1 {
478 end -= 1;
479 self.data.swap(0, end);
480 self.sift_down_range(0, end);
481 }
482 self.into_vec()
483 }
484
485 // The implementations of sift_up and sift_down use unsafe blocks in
486 // order to move an element out of the vector (leaving behind a
487 // zeroed element), shift along the others and move it back into the
488 // vector over the junk element. This reduces the constant factor
489 // compared to using swaps, which involves twice as many moves.
490 fn sift_up(&mut self, start: usize, mut pos: usize) {
491 unsafe {
492 let new = replace(&mut self.data[pos], zeroed());
493
494 while pos > start {
495 let parent = (pos - 1) >> 1;
496
497 if new <= self.data[parent] { break; }
498
499 let x = replace(&mut self.data[parent], zeroed());
500 ptr::write(&mut self.data[pos], x);
501 pos = parent;
502 }
503 ptr::write(&mut self.data[pos], new);
504 }
505 }
506
507 fn sift_down_range(&mut self, mut pos: usize, end: usize) {
508 unsafe {
509 let start = pos;
510 let new = replace(&mut self.data[pos], zeroed());
511
512 let mut child = 2 * pos + 1;
513 while child < end {
514 let right = child + 1;
515 if right < end && !(self.data[child] > self.data[right]) {
516 child = right;
517 }
518 let x = replace(&mut self.data[child], zeroed());
519 ptr::write(&mut self.data[pos], x);
520 pos = child;
521 child = 2 * pos + 1;
522 }
523
524 ptr::write(&mut self.data[pos], new);
525 self.sift_up(start, pos);
526 }
527 }
528
529 fn sift_down(&mut self, pos: usize) {
530 let len = self.len();
531 self.sift_down_range(pos, len);
532 }
533
534 /// Returns the length of the binary heap.
535 #[stable(feature = "rust1", since = "1.0.0")]
536 pub fn len(&self) -> usize { self.data.len() }
537
538 /// Checks if the binary heap is empty.
539 #[stable(feature = "rust1", since = "1.0.0")]
540 pub fn is_empty(&self) -> bool { self.len() == 0 }
541
542 /// Clears the binary heap, returning an iterator over the removed elements.
543 ///
544 /// The elements are removed in arbitrary order.
545 #[inline]
546 #[unstable(feature = "collections",
547 reason = "matches collection reform specification, waiting for dust to settle")]
548 pub fn drain(&mut self) -> Drain<T> {
549 Drain { iter: self.data.drain() }
550 }
551
552 /// Drops all items from the binary heap.
553 #[stable(feature = "rust1", since = "1.0.0")]
554 pub fn clear(&mut self) { self.drain(); }
555 }
556
557 /// `BinaryHeap` iterator.
558 #[stable(feature = "rust1", since = "1.0.0")]
559 pub struct Iter <'a, T: 'a> {
560 iter: slice::Iter<'a, T>,
561 }
562
563 // FIXME(#19839) Remove in favor of `#[derive(Clone)]`
564 #[stable(feature = "rust1", since = "1.0.0")]
565 impl<'a, T> Clone for Iter<'a, T> {
566 fn clone(&self) -> Iter<'a, T> {
567 Iter { iter: self.iter.clone() }
568 }
569 }
570
571 #[stable(feature = "rust1", since = "1.0.0")]
572 impl<'a, T> Iterator for Iter<'a, T> {
573 type Item = &'a T;
574
575 #[inline]
576 fn next(&mut self) -> Option<&'a T> { self.iter.next() }
577
578 #[inline]
579 fn size_hint(&self) -> (usize, Option<usize>) { self.iter.size_hint() }
580 }
581
582 #[stable(feature = "rust1", since = "1.0.0")]
583 impl<'a, T> DoubleEndedIterator for Iter<'a, T> {
584 #[inline]
585 fn next_back(&mut self) -> Option<&'a T> { self.iter.next_back() }
586 }
587
588 #[stable(feature = "rust1", since = "1.0.0")]
589 impl<'a, T> ExactSizeIterator for Iter<'a, T> {}
590
591 /// An iterator that moves out of a `BinaryHeap`.
592 #[stable(feature = "rust1", since = "1.0.0")]
593 pub struct IntoIter<T> {
594 iter: vec::IntoIter<T>,
595 }
596
597 #[stable(feature = "rust1", since = "1.0.0")]
598 impl<T> Iterator for IntoIter<T> {
599 type Item = T;
600
601 #[inline]
602 fn next(&mut self) -> Option<T> { self.iter.next() }
603
604 #[inline]
605 fn size_hint(&self) -> (usize, Option<usize>) { self.iter.size_hint() }
606 }
607
608 #[stable(feature = "rust1", since = "1.0.0")]
609 impl<T> DoubleEndedIterator for IntoIter<T> {
610 #[inline]
611 fn next_back(&mut self) -> Option<T> { self.iter.next_back() }
612 }
613
614 #[stable(feature = "rust1", since = "1.0.0")]
615 impl<T> ExactSizeIterator for IntoIter<T> {}
616
617 /// An iterator that drains a `BinaryHeap`.
618 #[unstable(feature = "collections", reason = "recent addition")]
619 pub struct Drain<'a, T: 'a> {
620 iter: vec::Drain<'a, T>,
621 }
622
623 #[stable(feature = "rust1", since = "1.0.0")]
624 impl<'a, T: 'a> Iterator for Drain<'a, T> {
625 type Item = T;
626
627 #[inline]
628 fn next(&mut self) -> Option<T> { self.iter.next() }
629
630 #[inline]
631 fn size_hint(&self) -> (usize, Option<usize>) { self.iter.size_hint() }
632 }
633
634 #[stable(feature = "rust1", since = "1.0.0")]
635 impl<'a, T: 'a> DoubleEndedIterator for Drain<'a, T> {
636 #[inline]
637 fn next_back(&mut self) -> Option<T> { self.iter.next_back() }
638 }
639
640 #[stable(feature = "rust1", since = "1.0.0")]
641 impl<'a, T: 'a> ExactSizeIterator for Drain<'a, T> {}
642
643 #[stable(feature = "rust1", since = "1.0.0")]
644 impl<T: Ord> FromIterator<T> for BinaryHeap<T> {
645 fn from_iter<I: IntoIterator<Item=T>>(iter: I) -> BinaryHeap<T> {
646 BinaryHeap::from_vec(iter.into_iter().collect())
647 }
648 }
649
650 #[stable(feature = "rust1", since = "1.0.0")]
651 impl<T: Ord> IntoIterator for BinaryHeap<T> {
652 type Item = T;
653 type IntoIter = IntoIter<T>;
654
655 /// Creates a consuming iterator, that is, one that moves each value out of
656 /// the binary heap in arbitrary order. The binary heap cannot be used
657 /// after calling this.
658 ///
659 /// # Examples
660 ///
661 /// ```
662 /// # #![feature(collections)]
663 /// use std::collections::BinaryHeap;
664 /// let heap = BinaryHeap::from_vec(vec![1, 2, 3, 4]);
665 ///
666 /// // Print 1, 2, 3, 4 in arbitrary order
667 /// for x in heap.into_iter() {
668 /// // x has type i32, not &i32
669 /// println!("{}", x);
670 /// }
671 /// ```
672 fn into_iter(self) -> IntoIter<T> {
673 IntoIter { iter: self.data.into_iter() }
674 }
675 }
676
677 #[stable(feature = "rust1", since = "1.0.0")]
678 impl<'a, T> IntoIterator for &'a BinaryHeap<T> where T: Ord {
679 type Item = &'a T;
680 type IntoIter = Iter<'a, T>;
681
682 fn into_iter(self) -> Iter<'a, T> {
683 self.iter()
684 }
685 }
686
687 #[stable(feature = "rust1", since = "1.0.0")]
688 impl<T: Ord> Extend<T> for BinaryHeap<T> {
689 fn extend<I: IntoIterator<Item=T>>(&mut self, iterable: I) {
690 let iter = iterable.into_iter();
691 let (lower, _) = iter.size_hint();
692
693 self.reserve(lower);
694
695 for elem in iter {
696 self.push(elem);
697 }
698 }
699 }