X-Git-Url: https://git.lizzy.rs/?a=blobdiff_plain;f=library%2Falloc%2Fsrc%2Fcollections%2Fbinary_heap.rs;h=a6bd554c5c3b2efa90f85ac2389fdc5ae5272883;hb=1b83fedda46d0162952d00f25a60c22028c1e15a;hp=b5e66d37ab494bfc8f95ac2fbf761ec21e87507e;hpb=1df20569dd07d91ed270ea9cfc2dbb9f56700703;p=rust.git diff --git a/library/alloc/src/collections/binary_heap.rs b/library/alloc/src/collections/binary_heap.rs index b5e66d37ab4..a6bd554c5c3 100644 --- a/library/alloc/src/collections/binary_heap.rs +++ b/library/alloc/src/collections/binary_heap.rs @@ -209,6 +209,14 @@ /// assert!(heap.is_empty()) /// ``` /// +/// A `BinaryHeap` with a known list of items can be initialized from an array: +/// +/// ``` +/// use std::collections::BinaryHeap; +/// +/// let heap = BinaryHeap::from([1, 5, 2]); +/// ``` +/// /// ## Min-heap /// /// Either `std::cmp::Reverse` or a custom `Ord` implementation can be used to @@ -958,6 +966,27 @@ pub fn shrink_to(&mut self, min_capacity: usize) { self.data.shrink_to(min_capacity) } + /// Returns a slice of all values in the underlying vector, in arbitrary + /// order. + /// + /// # Examples + /// + /// Basic usage: + /// + /// ``` + /// #![feature(binary_heap_as_slice)] + /// use std::collections::BinaryHeap; + /// use std::io::{self, Write}; + /// + /// let heap = BinaryHeap::from(vec![1, 2, 3, 4, 5, 6, 7]); + /// + /// io::sink().write(heap.as_slice()).unwrap(); + /// ``` + #[unstable(feature = "binary_heap_as_slice", issue = "83659")] + pub fn as_slice(&self) -> &[T] { + self.data.as_slice() + } + /// Consumes the `BinaryHeap` and returns the underlying vector /// in arbitrary order. /// @@ -1422,6 +1451,22 @@ fn from(vec: Vec) -> BinaryHeap { } } +#[stable(feature = "std_collections_from_array", since = "1.56.0")] +impl From<[T; N]> for BinaryHeap { + /// ``` + /// use std::collections::BinaryHeap; + /// + /// let mut h1 = BinaryHeap::from([1, 4, 2, 3]); + /// let mut h2: BinaryHeap<_> = [1, 4, 2, 3].into(); + /// while let Some((a, b)) = h1.pop().zip(h2.pop()) { + /// assert_eq!(a, b); + /// } + /// ``` + fn from(arr: [T; N]) -> Self { + core::array::IntoIter::new(arr).collect() + } +} + #[stable(feature = "binary_heap_extras_15", since = "1.5.0")] impl From> for Vec { /// Converts a `BinaryHeap` into a `Vec`.