?面向?qū)ο蟪绦蛟O(shè)計(jì)擴(kuò)展技術(shù) (一)模板 第 1 題 【要求】編寫一個對具有 n 個元素的數(shù)組 x 求最大值的程序,要求 將求最大值的函數(shù)設(shè)計(jì)成函數(shù)模板。 【源代碼】 #include<iostream> using namespace std; template<class T> T max(T x[],int n) { int i; T maxv=x[0]; for(i=1;i<n; i++) if(maxv<x[i]) maxv=x[i]; return maxv; } void main() { int a[]={4,5,2,8,9,3}; double b[]={3.5,6.7,2,5.2,9.2}; cout<<"數(shù)組最大值:"<<max(a,6)<<endl; cout<<"b 數(shù)組最大值:"<<max(b,5)<<endl; }
|
|