?面向對象程序設計擴展技術 (一)模板 第 1 題 【要求】編寫一個對具有 n 個元素的數組 x 求最大值的程序,要求 將求最大值的函數設計成函數模板。 【源代碼】 #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<<"數組最大值:"<<max(a,6)<<endl; cout<<"b 數組最大值:"<<max(b,5)<<endl; }
|
|