1. template <class BidirectionIterator>                                              
  2. bool next_permutation(BidirectionIterator first, BidirectionIterator last) {
  3.     if(first == last) return false;                                               
  4.     BidirectionIterator i = first;                                                
  5.     ++i;                                                                          
  6.     if(i == last) return false;                                                   
  7.     i = last;                                                                     
  8.     --i;                                                                          
  9.                                                                                   
  10.     for(;;) {                                                                     
  11.         BidirectionIterator ii = i;                                               
  12.         --i;                                                                      
  13.                                                                                   
  14.         if(*i < *ii) {                                                            
  15.             BidirectionIterator j = last;                                         
  16.             while(!(*i < *--j));                                                  
  17.             iter_swap(i, j);                                                      
  18.             reverse(ii, last);                                                    
  19.             return true;                                                          
  20.         }                                                                         
  21.                                                                                   
  22.         if(i == first) {                                                          
  23.             reverse(first, last);                                                 
  24.             return false;                                                         
  25.         }                                                                         
  26.     }