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

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.