STL源码剖析之算法:pop_heap

  
  
  
  
  1. template <class RandomAccessIterator> 
  2. inline void pop_heap(RandomAccessIterator first, RandomAccessIterator last) { 
  3.     __pop_heap_aux(first, last, value_type(first)); 
  4.  
  5. template <class RandomAccessIterator, class T> 
  6. inline void __pop_heap_aux(RandomAccessIterator first, RandomAccessIterator last, T*) { 
  7.     __pop_heap(first, last - 1, last - 1, T(*(last-1)), distance_type(first)); 

 

  
  
  
  
  1. template <class RandomAccessIterator, class T, class Distance> 
  2. inline void __pop_heap(RandomAccessIterator first, 
  3.                      RandomAccessIterator last, 
  4.                      RandomAccessIterator result, 
  5.                      T value, Distance*) { 
  6.     *result = *first; 
  7.     __adjust_heap(first, Distance(0), Distance(last - first), value); 
  8.  
  9. template <class RandomAccessIterator, class Distance, class T>                    
  10. void __adjust_heap(RandomAccessIterator first, Distance holeIndex,                
  11.                    Distance len, T vaule) {                                       
  12.     Distance topIndex = holeIndex;                                                
  13.     Distance secondChild = holeIndex*2 + 2;                                       
  14.                                                                                   
  15.     while(secondChild < len) {                                                    
  16.         if(*(first + secondChild) < *(first + secondChild - 1))                   
  17.             --secondChild;                                                        
  18.                                                                                   
  19.         *(first + holeIndex) = *(first + secondChild);                            
  20.         holeIndex = secondChild;                                                  
  21.         secondChild = holeIndex*2 + 2;                                            
  22.     }                                                                             
  23.                                                                                   
  24.     if(secondChild == len) {                                                      
  25.         *(first + holeIndex) = *(first + secondChild - 1);                        
  26.         holeIndex = secondChild - 1;                                              
  27.     }                                                                             
  28.                                                                                   
  29.     __push_heap(first, holeIndex, topIndex, vaule);                               

注:__push_heap的源码请见 http://zxn990.blog.51cto.com/4253193/1165513

你可能感兴趣的:(heap,STL,pop_heap)