I l@ve RuBoard Previous Section Next Section

Exercise 2.3

Separate the function to calculate the Pentagonal numeric sequence implemented in Exercise 2.2 into two functions. One function should be inline; it checks the validity of the position. A valid position not as yet calculated causes the function to invoke a second function that does the actual calculation.

I factored calc_elements() into the inline calc_elems() that if necessary calls the second function, really_calc_elems(). To test this reimplementation, I substituted the call of calc_elements() in the Exercise 2.2 function with that of calc_elems().



extern void really_calc_elems( vector<int>&, int ); 


inline bool calc_elems( vector<int> &vec, int pos ) 


{ 


   if ( pos <= 0 || pos > 64 ){ 


        cerr << "Sorry. Invalid position: " << pos << endl; 


        return false; 


   } 





   if ( vec.size() < pos ) 


        really_calc_elems( vec, pos ); 


   return true; 


} 


void really_calc_elems( vector<int> &vec, int pos ) 


{ 


   for ( int ix = vec.size()+1; ix <= pos; ++ix ) 


         vec.push_back( (ix*(3*ix-1))/2 ); 


} 
    I l@ve RuBoard Previous Section Next Section