C++Primer Plus 编程练习8.8,练习6函数重载和函数模板的实现

6.编写模板函数 maxn(),它将由一个T类型元素组成的数组和一个表示数组元素数目的整数作为参数,
并返回数组中最大的元素。在程序对它进行测试,该程序使用一个包含6个int元素的数组和一个包含4个double
元素的数组来调用该函数。程序还包含一个具体化,它将char指针数组和数组中的指针数量作为参数,
并返回最长的字符串的地址。如果有多个这样的字符串,则返回其中第一个字符串的地址。
使用由5个字符串指针组成的数组来测试该具体化。*/

#pragma region 练习6.cpp
/*

#if 1
#include <iostream>
#include <string>
template<typename T>
const T& maxn(const T arr[], unsigned n);
const char* maxn(const char* arr[], unsigned n);
int main()
{
	using namespace std;
	int intArray[] = { 1,2,3,4,5,6 };
	for (const auto&e:intArray)
	{
		cout << e << " ";
	}
	cout << " ----max: " << maxn(intArray, sizeof(intArray) / sizeof(intArray[0])) << endl;
	cout << endl;
	double doubleArray[] = { 7.1,2.2,3.2,4.4 };
	for (const auto& e : doubleArray)
	{
		cout << e << " ";
	}
	cout << " ----max: " << maxn(doubleArray, sizeof(doubleArray) / sizeof(doubleArray[0])) << endl;
	cout << endl;

	const char* szArray[] = {
		"aa aa",
		"dddddddddddd",
		" ",
		"ffffff   fffff",
		"gg ggg",
	};
	for (const auto&e:szArray)
	{
		cout << "\"" << e << "\"" << " ";
	}
	cout << " ------max: " << "\"" << maxn(szArray, sizeof(szArray) / sizeof(szArray[0])) << "\"" << endl;
	cout << endl;
	return 0;
}
template<typename T>
const T& maxn(const T arr[], unsigned n)
{
	unsigned arrMaxId = 0;
	for (unsigned i = 0; i < n; i++)
	{
		if (arr[i]>arr[arrMaxId])
		{
			arrMaxId = i;
		}
	}
	return (arr[arrMaxId]);
}
const char* maxn(const char* arr[], unsigned n)
{
	unsigned arrLenMaxId = 0;
	for (unsigned i = 0; i < n; i++)
	{
		if (strlen(arr[i])>strlen(arr[arrLenMaxId]))
		{
			arrLenMaxId = i;
		}
	}
	return arr[arrLenMaxId];
}
#endif
#pragma endregion

第五题是第六题的生化,进一步学习

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

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值