當前位置:編程學習大全網 - 編程軟體 - C++編程:定義模板函數,返回基本類型數組中最大值或最小值(主函數驗證),咋寫?

C++編程:定義模板函數,返回基本類型數組中最大值或最小值(主函數驗證),咋寫?

代碼文本:

//#include "stdafx.h"//vc++ 6.0? Maybe should add this line.

#include <iostream>

using namespace std;

template <typename T>//模板函數

T fun(T *p,int n,int x=0){

for(int maxi=0,mini=0,i=1;i<n;i++)?

if(p[maxi]<p[i])

maxi=i;

else if(p[mini]>p[i])

mini=i;

return? p[x ? mini : maxi];

}

int main(int argc,char *argv[]){//測試主函數

double a[3]={1.07,66.34,42.1};

int b[5]={1,2,3,4,5};

char s[]="abcdefg";

cout << "The results are as follows:\n";

cout << "MAX: " << fun(a,3) << '\t' << fun(b,5) << '\t' << fun(s,7) << endl;

cout << "MIN: " << fun(a,3,1) << '\t' << fun(b,5,1) << '\t' << fun(s,7,1) << endl;

return 0;

}

  • 上一篇:Geany按鈕沒有響應。
  • 下一篇:javascript的面向對象的編程介紹書籍有哪些
  • copyright 2024編程學習大全網