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.1. The Arithmetic of Pointers

We are assigned the following programming task. We are given a vector of integers and an integer value. If the value is contained within the vector, we must return a pointer to it; otherwise, we return 0, indicating that the value is not present. Here is an implementation:

int* find( const vector<int> &vec, int value ) 
{ 
    for ( int ix = 0; ix < vec.size(); ++ix ) 
          if ( vec[ ix ] == value ) 
               return &vec[ ix ]; 
    return 0; 
} 

We test the function and are satisfied that it works. We are next assigned the task of having the function work not only with integers but also with any type in which the equality operator is defined. If you have read Section 2.7, you should recognize this task as requiring us to transform find() ...

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