// TEMPLATE FUNCTION pop_heap WITH PRED
template<class _RanIt,
class _Diff,
class _Ty,
class _Pr> inline
void _Adjust_heap(_RanIt _First, _Diff _Hole, _Diff _Bottom,
_Ty&& _Val, _Pr _Pred)
{ // percolate _Hole to _Bottom, then push _Val, using _Pred
/*
_Hole为0,表示起点位置
_Bottom为begin()-end()-1,也就是数组长度减一
_Val保存着最后位置的值,也就是*(end()-1)
*/
_Diff _Top = _Hole;//_Top等于0
_Diff _Idx = 2 * _Hole + 2;//转到_Hole的右孩子处
for (; _Idx < _Bottom; _Idx = 2 * _Idx + 2)
{ // move _Hole down to larger child
if (_DEBUG_LT_PRED(_Pred, *(_First + _Idx), *(_First + (_Idx - 1))))
--_Idx;//_Idx指向左右孩子值较大(小)的位置
*(_First + _Hole) = _STD move(*(_First + _Idx));
_Hole = _Idx;
}
if (_Idx == _Bottom)
{ // only child at bottom, move _Hole down to it
*(_First + _Hole) = _STD move(*(_First + (_Bottom - 1)));
_Hole = _Bottom - 1;
}
_Push_heap(_First, _Hole, _Top, _STD move(_Val), _Pred);
}
template<class _RanIt,
class _Diff,
class _Ty,
class _Pr> inline
void _Pop_heap(_RanIt _First, _RanIt _Last, _RanIt _Dest,
_Ty&& _Val, _Pr _Pred, _Diff *)
{ // pop *_First to *_Dest and reheap, using _Pred
*_Dest = _STD move(*_First);//把第一个元素赋给最后一个,最后一个位置的值早已经保存在_Val
_Adjust_heap(_First, _Diff(0), _Diff(_Last - _First),
_STD move(_Val), _Pred);
}
template<class _RanIt,
class _Ty,
class _Pr> inline
void _Pop_heap_0(_RanIt _First, _RanIt _Last, _Pr _Pred, _Ty *)
{ // pop *_First to *(_Last - 1) and reheap, using _Pred
_Ty _Val = _STD move(*(_Last - 1));
_Pop_heap(_First, _Last - 1, _Last - 1,
_STD move(_Val), _Pred, _Dist_type(_First));
}
template<class _RanIt,
class _Pr> inline
void _Pop_heap(_RanIt _First, _RanIt _Last, _Pr _Pred)
{ // pop *_First to *(_Last - 1) and reheap, using _Pred
_Pop_heap_0(_Unchecked(_First), _Unchecked(_Last), _Pred,
_Val_type(_First));
}
template<class _RanIt,
class _Pr> inline
void pop_heap(_RanIt _First, _RanIt _Last, _Pr _Pred)
{ // pop *_First to *(_Last - 1) and reheap, using _Pred
_DEBUG_RANGE_PTR(_First, _Last, _Pred);
_DEBUG_HEAP_PRED(_First, _Last, _Pred);
if (2 <= _Last - _First)
_Pop_heap(_Unchecked(_First), _Unchecked(_Last), _Pred);
}
// TEMPLATE FUNCTION pop_heap
template<class _RanIt> inline
void pop_heap(_RanIt _First, _RanIt _Last)
{ // pop *_First to *(_Last - 1) and reheap, using operator<
_STD pop_heap(_First, _Last, less<>());
}