taken by a sudden spirit of rebellion I reread the paragraph on for_each and it (implicitly) allows side effects on its functor argument... mah...
therefore the following code should be standard correct
a presumably correct alternative with accumulate would beCode:int main() { char data[] = {0, 1, 2, 3, 0, 0, 4 ,5 ,0, 0, 0, 6, 7}; int count = 0; int largest = 0; std::for_each( data, data + 13, [&]( char value ) { if( value ) count = 0; else largest = std::max( largest, ++count ); } ); }
Code:int main() { char data[] = {0, 1, 2, 3, 0, 0, 4 ,5 ,0, 0, 0, 6, 7}; struct MyCounter { MyCounter(): value(0), count(0) {} MyCounter( int value, int count ): value(value), count(count) {} MyCounter operator+( char a_char ) { if( a_char ) count = 0; else ++count; return MyCounter( std::max( value, count ), count ); } int value; int count; }; MyCounter count = std::accumulate( data, data + 13, MyCounter() ); }





Reply With Quote