51

问答题 51 /76

Below is usual way we find one element in an array
const int *find1(const int* array, int n, int x)
{
    const int* p = array;
    for(int i = 0; i < n; i++)
    {
        if(*p == x)
        {
            return p;
        }
    ++p;
    }
    return 0; 
}
In this case we have to bear the knowledge of value type "int", the size of array, even the existence of an array. Would you re-write it using template to eliminate all these dependencies?

参考答案

template <class T>
const T *find1(const T* array, int n, T x)
{
    const T* p = array;
    for(int i = 0; i < n; i++)
    {
        if(*p == x)
        {
            return p;
        }
        ++p;
    }
    return 0; 
}