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,
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
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.