@@ -607,6 +607,56 @@ where
607
607
}
608
608
609
609
impl < T , C : Compare < T > > BinaryHeap < T , C > {
610
+ /// Replaces the comparator of binary heap.
611
+ ///
612
+ /// # Examples
613
+ ///
614
+ /// Basic usage:
615
+ ///
616
+ /// ```
617
+ /// use binary_heap_plus::*;
618
+ /// use compare::Compare;
619
+ /// use std::cmp::Ordering;
620
+ ///
621
+ /// struct Comparator {
622
+ /// ascending: bool
623
+ /// }
624
+ ///
625
+ /// impl Compare<i32> for Comparator {
626
+ /// fn compare(&self,l: &i32,r: &i32) -> Ordering {
627
+ /// if self.ascending {
628
+ /// r.cmp(l)
629
+ /// } else {
630
+ /// l.cmp(r)
631
+ /// }
632
+ /// }
633
+ /// }
634
+ ///
635
+ /// // construct a heap in ascending order.
636
+ /// let mut heap = BinaryHeap::from_vec_cmp(vec![3, 1, 5], Comparator { ascending: true });
637
+ ///
638
+ /// // replace the comparor
639
+ /// heap.replace_cmp(Comparator { ascending: false });
640
+ /// assert_eq!(heap.into_iter_sorted().collect::<Vec<_>>(), vec![5, 3, 1]);
641
+ /// ```
642
+ #[ inline]
643
+ pub fn replace_cmp ( & mut self , cmp : C ) {
644
+ unsafe {
645
+ self . replace_cmp_raw ( cmp, true ) ;
646
+ }
647
+ }
648
+
649
+ /// Replaces the comparator of binary heap.
650
+ ///
651
+ /// # Safety
652
+ /// User is responsible for providing valid `rebuild` value.
653
+ pub unsafe fn replace_cmp_raw ( & mut self , cmp : C , rebuild : bool ) {
654
+ self . cmp = cmp;
655
+ if rebuild && !self . data . is_empty ( ) {
656
+ self . rebuild ( ) ;
657
+ }
658
+ }
659
+
610
660
/// Returns an iterator visiting all values in the underlying vector, in
611
661
/// arbitrary order.
612
662
///
0 commit comments