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
第五题是第六题的生化,进一步学习