O'Reilly logo

Essential C++ by Stanley B. Lippman

Stay ahead with the world's most comprehensive technology and business learning platform.

With Safari, you learn the way you learn best. Get unlimited access to videos, live online training, learning paths, books, tutorials, and more.

Start Free Trial

No credit card required

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 ...

With Safari, you learn the way you learn best. Get unlimited access to videos, live online training, learning paths, books, interactive tutorials, and more.

Start Free Trial

No credit card required