【C++ Primer Plus习题】8.6

问题:

这里是引用

解答:

#include <iostream>
using namespace std;

template <typename T>
T maxn(T arr[], int len)//通用
{
	T max = 0;
	for (int i = 0; i < len; i++)
	{
		if (max < arr[i])
		{
			max = arr[i];
		}
	}
	return max;
}

template<>
const char* maxn<const char*>(const char* c[], int len)
{
	const char* p = c[0];
	int size = strlen(p);
	for (int i = 1; i < len; i++)
	{
		if (size < strlen(c[i]))
		{
			p = c[i];
		}
	}
	return p;
}



int main()
{
	int max = 0;
	double max1 = 0.0;
	int a1[6] = { 1,2,3,4,5,6 };
	double d1[4] = { 1.1,2.2,3.3,4.4 };
	max = maxn(a1, 6);
	max1 = maxn(d1, 4);
	cout << "int中最大的数为:" << max <<endl;
	cout << "double中最大的数为:" << max1 << endl;

	const char* p[5] = { "1","12","123","1234","12345" };
	const char* c= maxn(p, 5);
	cout << "字符数组中最长的字符为:" << c << endl;

	return 0;
}

运行结果:
在这里插入图片描述

考查点:

  • 模版函数
  • 模版函数具体化

注意:

  • 模版函数具体化会被优先调用
  • 可以自定义一些通用模版函数做不到的.
    在这里插入图片描述

2024年9月1日21:54:55

  • 2
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 1
    评论
评论 1
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值