泛型编程之3

63 篇文章 0 订阅
40 篇文章 0 订阅

题:

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;
}


  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值