首页 诗词 字典 板报 句子 名言 友答 励志 学校 网站地图
当前位置: 首页 > 教程频道 > 开发语言 > C++ >

函数模版,兑现数组最大元素输出

2012-08-13 
函数模版,实现数组最大元素输出这个程序可以运行,但是输出结果却不对,请大家帮忙看下哪里不对#include st

函数模版,实现数组最大元素输出
这个程序可以运行,但是输出结果却不对,请大家帮忙看下哪里不对
#include <stdio.h>
template <class type,int len>
type max(type array[len])
{
type ret=array[0];
for (int i=0;i<10;i++)
ret=(ret>array[i])?ret:array[i];
return ret;
}

void main ()
{
int array[5]={1,2,3,4,5};
int iret=max<int,5>(array);
printf("%d\n",iret);
double iarray[3]={10.36,44.22,11.98};
double iiret=max<double,3>(iarray);
printf("%f\n",iiret);
}


[解决办法]
for循环里写10干嘛?
[解决办法]

C/C++ code
template<typename T,size_t nLen>T Max(T (&Array)[nLen] ){    T ret=Array[0];    for( size_t i=0 ; i < nLen ; i++ )        ret = ( ret > Array[i] ) ? ret : Array[i];    return ret;}
[解决办法]
几个问题:
1.模板函数参数类型不对,应该使用引用参数,否则每次使用时还要显式指定数组的长度
2.函数内部应该使用len而不是10
3.type可能是类类型,在没有具名返回值优化的情况下,会多构造和析构一个ret对象

改成这样应该会更好点:
C/C++ code
template <class type,int len>type max(const type (&array)[len]){    int ind = 0;        for (int i = 1; i < len; i++)    {        if (array[i] > array[ind])        {            ind = i;        }    }        return array[ind];}
[解决办法]
探讨
几个问题:
1.模板函数参数类型不对,应该使用引用参数,否则每次使用时还要显式指定数组的长度
2.函数内部应该使用len而不是10
3.type可能是类类型,在没有具名返回值优化的情况下,会多构造和析构一个ret对象

改成这样应该会更好点:

C/C++ code


template <class type,int len>
type max(const type (&a……

[解决办法]
C/C++ code
template <class type,int len>type max(type array[len]){type ret=array[0];for (int i=0;i<10;i++)ret=(ret>array[i])?ret:array[i];return ret;} 

热点排行