CodeGuru Home VC++ / MFC / C++ .NET / C# Visual Basic VB Forums Developer.com
Results 1 to 15 of 68

Threaded View

  1. #16
    Join Date
    Oct 2008
    Posts
    1,456

    Re: counting consecutive null characters

    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

    Code:
    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 ); } );
    }
    a presumably correct alternative with accumulate would be

    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() );
    }
    Last edited by superbonzo; April 15th, 2010 at 09:23 AM. Reason: added alternative

Posting Permissions

  • You may not post new threads
  • You may not post replies
  • You may not post attachments
  • You may not edit your posts
  •  





Click Here to Expand Forum to Full Width

Featured