for_each that gives two (or n) adjacent elements

后端 未结 4 1972
失恋的感觉
失恋的感觉 2020-12-29 21:53

Is there a standard implementation of a for_each that does call with the element and the next one in the range?

For example take the range {0, 1,

4条回答
  •  情话喂你
    2020-12-29 22:10

    The simplest thing would be to write it as a generic algorithm, then apply it many times.

     template< typename FwdIter, typename Func >
     Func for_each_pair( FwdIter iterStart, FwdIter iterEnd, Func func )
     {
         if( iterStart == iterEnd )
            return func;
    
         FwdIter iterNext = iterStart;
         ++iterNext;
    
         for( ; iterNext != iterEnd; ++iterStart, ++iterNext )
         {
              func( *iterStart, *iterNext );
         }
         return func;
    }
    

    As I was asked why it returns func (rather than void), this is typical of a for_each because of the fact that

    1. func could be an object
    2. It is passed by value.

    func may "accumulate" some kind of state, but it is the copy we have made into this algorithm that is accumulating it, not the user's original object. We therefore pass them back the modified "func" object.

提交回复
热议问题