第9章模板 例92(续一) template <class t> void Insertion SortT Al, int n) int 1, T temp for(i=1; i<n; 1++) ∥从A[-1开始向A[0]方向扫描各元素寻找适当位置插入AU =i; temp= A[; whle〔>0&&temp≤A[-们) ∥遇到temp>≡AU-们结束循环时,j便是应插入的位置 ∥遇到==0结束循环时,则0是应插入的位置 A]=A-];∥将元素逐个后移,以便找到插入位置时可立即插入。 A0= temp;
例9.2 (续一) template <class T> void InsertionSort(T A[], int n) { int i, j; T temp; for (i = 1; i < n; i++) { //从A[i-1]开始向A[0]方向扫描各元素,寻找适当位置插入A[i] j = i; temp = A[i]; while (j > 0 && temp < A[j-1]) { //当遇到temp>=A[j-1]结束循环时,j便是应插入的位置 //当遇到j==0结束循环时,则0是应插入的位置。 A[j] = A[j-1]; //将元素逐个后移,以便找到插入位置时可立即插入。 j--; } A[j] = temp; } } 第9章 模板
第9章模板 例92(续二) include <iostream.h> void maino inta[10]={2,4,187,9,0356} double b[10]={121,242,15.5,817,27,59,403,333,256,4.6}; Insertion Sort(a, 10); Insertion Sort(b, 10); cout≤a<""≤可1<<""≤a[2]<""≤a3<""; cout < a4<<""a5""a6]<""κ叫" cout < a[8] a[9]<<endl; cout<b[0]<""<b1<<""<b[2]<""<b[3]<" cout<bp4]""sb5]""≤<b6]<""≤b7]<""; cout < b[8]<<<< b[9]<<endl; 程序运行结果为: 0123456789 2.74.65.912.115.524.225.633.340.381.7
例9.2 (续二) #include <iostream.h> void main() { int a[10]={2,4,1,8,7,9,0,3,5,6}; double b[10]={12.1, 24.2, 15.5, 81.7, 2.7, 5.9, 40.3, 33.3, 25.6, 4.6}; InsertionSort(a,10); InsertionSort(b,10); cout << a[0] << " " << a[1]<< " " << a[2] << " " << a[3] << " "; cout << a[4] << " " << a[5]<< " " << a[6] << " " << a[7] << " "; cout << a[8] << " " << a[9]<< endl; cout << b[0] << " " << b[1]<< " " << b[2] << " " << b[3] << " "; cout << b[4] << " " << b[5]<< " " << b[6] << " " << b[7] << " "; cout << b[8] << " " << b[9]<< endl; } 第9章 模板 程序运行结果为: 0 1 2 3 4 5 6 7 8 9 2.7 4.6 5.9 12.1 15.5 24.2 25.6 33.3 40.3 81.7
第9章模板 例9.3使用函数模板产生的二意性 include <iostream.h> template <class T> T max(T a, T b) 产生二意性,系统不能确定将其中的 return a>b?a: b: 个参数由整数转化为实数,还是应该将 另一个参数由实数转化为整数 void main(void) 可使用强制类型转换解决 int a =max( (int)10.5, 20); inta=max(10.5,20); double b=max((double)10, 20.6); double b=max(10, 20.6); cout<≤a<<endl; cout < b<< endl 返回
例9.3 使用函数模板产生的二意性 #include <iostream.h> template <class T> T max(T a, T b) { return a>b?a:b; } void main(void) { int a = max(10.5, 20); double b = max(10, 20.6); cout << a << endl; cout << b << endl; } 第9章 模板 产生二意性,系统不能确定将其中的一 个参数由整数转化为实数,还是应该将 另一个参数由实数转化为整数。 可使用强制类型转换解决: int a =max( (int)10.5, 20); double b =max( (double ) 10, 20.6); 返 回