// GenericMaxjump.cpp // NKU CSC 601 - Fall 2002 - Kirby // ------------------------------------------------------------------------- // An introduction to generic programming in C++: // a generic function for computing the adjacent change of maximal // magnitude in a sequence of numbers. // // Generic along 2 dimensions: "sequence" and "number". // // This is NOT the final solution in STL. (We will soon use functors and get rid // of the loop, for example.) But it is the end of the road in generality. // // This is "Version 7" in our "Road to GenericLand" lecture of Oct. 3. // // Compiles w/ Borland C++ 5.5.1 (Win) and MetroWerks Code Warrior 4.0 (Mac). // ------------------------------------------------------------------------- #include #include #include #include #include using namespace std ; template< typename TNum > // // TNum: value ( <, unary- ) ; // TNum ab( TNum x ) // General absolute value. { return x < 0 ? -x : x ; } template< typename ItNum > // // ItNum: iterator (forward const) to value ( <, unary-, binary- ) ; // typename iterator_traits::value_type maxjump( ItNum first, ItNum last ) // // Return the adjacent change of maximal magnitude in a sequence of numbers. // { typedef typename iterator_traits::value_type TNum ; TNum maxjump= 0 ; ItNum it= first ; TNum cur= *it++ ; assert( it != last ) ; // sequence length > 1 while ( it != last ) { TNum jump= *it - cur ; if ( ab(jump) > ab(maxjump) ) maxjump= jump ; cur= *it++ ; } return maxjump ; } int main() { // Check out 8 possibilities. double xarr[]= { 12.3, 16.5, 10.4, 15.3, 8.8, 4.3 } ; vector xvec( xarr, xarr+6 ) ; deque xdeq( xarr, xarr+6 ) ; list xlis( xarr, xarr+6 ) ; int iarr[]= { 4, 6, -10, 100, 3, 9 } ; vector ivec( iarr, iarr+6 ) ; deque ideq( iarr, iarr+6 ) ; list ilis( iarr, iarr+6 ) ; cout << "Vector of doubles: " << maxjump( xvec.begin(), xvec.end() ) << endl ; cout << "Deque of doubles: " << maxjump( xdeq.begin(), xdeq.end() ) << endl ; cout << "List of doubles: " << maxjump( xlis.begin(), xlis.end() ) << endl ; cout << "C array of doubles: " << maxjump( xarr, xarr+6 ) << endl ; cout << "Vector of ints: " << maxjump( ivec.begin(), ivec.end() ) << endl ; cout << "Deque of ints: " << maxjump( ideq.begin(), ideq.end() ) << endl ; cout << "List of ints: " << maxjump( ilis.begin(), ilis.end() ) << endl ; cout << "C array of ints: " << maxjump( iarr, iarr+6 ) << endl ; return 0 ; } /* Note: ---- In maxjump(), assert( first != last ) does not assert there is more than 1 element. It asserts there are more than 0 elements. (So we don't use it.) */