题:
Below is usual way we find one element in an array: 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?(我们通常求解一个数在一个数列里的方法是这样的:在这个例子中,我们得先知道int类型的知识,知道队列的大小,甚至要建立一个队列。你能否用泛型编程模拟这个队列,做到不知道上面的附加知识仍然能得出结果?)【德国某著名软件咨询企业2004年面试题】
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;
}
解析:这是一个把普通函数改成泛型函数的问题,在这里公司考的是如何将普通函数转换成泛型函数。
答案:
修改代码如下:
template <typename T>
const T* My_find(T* array, T n, T x)
{
const T* p = array;
int i;
for(i = 0; i < n; ++i)
{
if(*p == x)
return p;
++p;
}
return 0;
}
或者:
template <typename T>
const T* My_find2(const T* s, const T* e, T x)
{
const T* p = s;
while(p !=e)
{
if(*p == x)
return p;
++p;
}
return e;
}