编程练习6.
要求包含一个具体化,将char指针数组和数组中的指针数量作为参数,并返回最长的字符串地址。如有多个这样的字符串,返回其中第一个字符串的地址。使用由5个字符串指针组成的数组来测试该具体化。
#include <iostream>
#include <cstring>
using namespace std;
template <typename T>
T maxn(T str[], int n);
template <> char* maxn(char* p[], int n);
int main()
{
int a[6] = { 5,7,3,11,9 ,8 };
double b[4] = { 5.1,11.4,3.6,9.5 };
int n;
double d;
n = maxn(a, 6);
d = maxn(b, 4);
cout << "int数组最大值为:" << n << endl;
cout << "double数组最大值为:" << d << endl;
cout << endl;
cout << endl;
const char* p[5] = { "asdf","svb","asasddsf","adfsfasd","sasdf" };
const char* pm;
pm = maxn(p, 5);
for (int i = 0; i < 5; i++)
cout << "p[" << i << "]的字符串为:" << *(p + i) << " ,地址为:" << (p + i) << " ,长度为:" << strlen(p[i]) << endl;
cout << "第一个最长的字符串的地址为:" << ±
return 0;
}
template <typename T>
T maxn(T str[], int n)
{
T temp = str[0];
for (int i = 0; i < n; i++)
{
if (str[i] > temp)
temp = str[i];
}
return temp;
}
template <> char* maxn(char* a[], int n) {
int temp = 0;
int j = 0;
for (int i = 0; i < n; i++) {
if (temp < (int)strlen(a[i])) {
temp = strlen(a[i]);
j = i;
}
else
continue;
}
char* p = a[j];
return p;
}
为什么最后得到的结果并不是指针数组中的地址而在数组外?并且输出的字符串也并非最长。。。
大概是具体化实现出了问题但不知道问题出在哪里求大佬解惑。。。