February 24, 2014

Below is a collection of examples of common code patterns that could otherwise be written simpler, cleaner, and more correct when the STL or boost is used.

Call a Function with Each Value in a Sequence

for ( size_t x = 0 ; x < v. size ( ) ; x ++ ) { func ( v [ x ] ) ; }

std :: for_each ( v. begin ( ) , v. end ( ) , func ) ;

Get the Sum of a Sequence

long long z = 0 ; for ( size_t x = 0 ; x < v. size ( ) ; x ++ ) { z += v [ x ] ; }

long long z = std :: accumulate ( v. begin ( ) , v. end ( ) , 0LL ) ;

Be careful with std::accumulate.

Get the Product of a Sequence

long long z = 1 ; for ( size_t x = 0 ; x < v. size ( ) ; x ++ ) { z *= v [ x ] ; }

long long z = std :: accumulate ( v. begin ( ) , v. end ( ) , 1 , std :: multiplies < long long > ( ) ) ;

Write the Values of a Sequence to a Stream

std :: ostringstream ss ; for ( size_t x = 0 ; x < v. size ( ) ; x ++ ) { ss << v [ x ] << "

" ; }

std :: ostringstream ss ; std :: copy ( v. begin ( ) , v. end ( ) , std :: ostream_iterator < int > ( ss , "

" ) ) ;

Read the Contents of a File Into a String

std :: string data ; std :: ifstream in ( filename. c_str ( ) ) ; do { char ch = in. get ( ) ; if ( in ) { data. push_back ( ch ) ; } } while ( in ) ;

std :: string data ; std :: ifstream in ( filename. c_str ( ) ) ; std :: copy ( std :: istreambuf_iterator < char > ( in ) , std :: istreambuf_iterator < char > ( ) , std :: back_inserter ( data ) ) ;

Reverse a Sequence

for ( size_t i = 0 ; i < v. size ( ) / 2 ; i ++ ) { std :: swap ( v [ v. size ( ) - i - 1 ] , v [ i ] ) ; }

std :: reverse ( v. begin ( ) , v. end ( ) ) ;

Fill a Sequence With Generated Values

int RandomNumber ( ) { return ( std :: rand ( ) % 100 ) ; } std :: srand ( unsigned ( std :: time ( 0 ) ) ) ; std :: vector < int > v ; for ( size_t x = 0 ; x < 10 ; x ++ ) { v. push_back ( RandomNumber ( ) ) ; }