3.6. How to Design a Generic Algorithm

Here is our task. We are given a vector of integer values. We are asked to return a new vector holding all the values that are less than 10. A quick but inflexible solution is the following:

vector<int> less_than_10( const vector<int> &vec ) 
{ 
    vector<int> nvec; 
    for ( int ix = 0; ix < vec.size(); ++ix ) 
          if ( vec[ ix ] < 10 ) 
               nvec.push_back( vec[ ix ] ); 
    return nvec; 
} 

If the user wants all the elements less than 11, we must either create a new function or generalize this one to allow the user to specify a value against which to compare the elements. For example,

vector<int> less_than( const vector<int> &vec, int less_than_val ); 

But our next task is actually somewhat more difficult. We must allow the ...

Get Essential C++ now with the O’Reilly learning platform.

O’Reilly members experience books, live events, courses curated by job role, and more from O’Reilly and nearly 200 top publishers.