首页 > 试题广场 >

using template to eliminate al

[问答题]
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; 
}

编辑于 2015-02-04 10:07:09 回复(0)
template<classT,int n>
constT *find1(constT (&array)[n], T x)
{
    constT* p = array;
    for(inti = 0; i < n; i++)
    {
        if(*p == x)
        {
            returnp;
        }
        ++p;
    }
    return0;
}
发表于 2015-08-30 10:18:06 回复(0)