1 #include<iostream> 2 using namespace std; 3 4 template<class T> 5 class mypair { 6 T a, b; 7 public: 8 mypair(T first, T second) 9 { 10 a = first; 11 b = second; 12 } 13 T getmax(); 14 }; 15 16 template<class T> 17 T mypair<T>::getmax() 18 { 19 T retval; 20 retval = a > b ? a : b; 21 return retval; 22 } 23 24 int main() { 25 mypair<int>myobject(100, 75); 26 cout << myobject.getmax(); 27 return 0; 28 } 29 30 #include<iostream> 31 using namespace std; 32 33 template <class T,int N> 34 class mysequence { 35 T memblock[N]; 36 public: 37 void setmember(int x, T value); 38 T getmember(int x); 39 }; 40 41 template <class T,int N> 42 void mysequence<T, N>::setmember(int x, T value) 43 { 44 memblock[x] = value; 45 } 46 47 template<class T,int N> 48 T mysequence<T, N>::getmember(int x) 49 { 50 return memblock[x]; 51 } 52 53 int main() { 54 mysequence<int, 5>myints; 55 mysequence<double, 5>myfloats; 56 myints.setmember(0, 100); 57 myfloats.setmember(3, 3.1416); 58 cout << myints.getmember(0) << '\n'; 59 cout << myfloats.getmember(3) << '\n'; 60 return 0; 61 }
1 #include<iostream> 2 using namespace std; 3 4 template<class T> 5 void swapData(T& a, T& b) 6 { 7 T t = a; 8 a = b; 9 b = t; 10 } 11 /*直接选择排序,要求:小的在前大的在后*/ 12 template<class T> 13 void selectSort(T a[], int n) 14 { 15 int i, j, k, t; 16 int tmp; 17 18 for (i = 0; i < n - 1; i++) /*i比j小1,所以i范围是0~n-1*/ 19 { 20 k = i; /*最小值下标*/ 21 for (j = i + 1; j < n; j++) 22 if (a[j] < a[k]) 23 k = j; 24 swapData(a[i], a[k]); 25 for (k = 0;k < n;k++) 26 cout << a[k] << " "; 27 cout << endl; 28 } 29 } 30 int main() 31 { 32 int a[] = { 1,3,5,7,9,11,13,15,17,19,2,4,6,8,10,12,14,16,18,20 }; 33 34 cout << "排序前的数据:" << endl; 35 for (int i = 0; i < 20; i++) 36 cout << a[i] << " "; 37 cout << endl; 38 39 cout << "进行排序:" << endl; 40 selectSort(a, 20); 41 42 cout << "排序后的数据:" << endl; 43 for (int i = 0; i < 20; i++) 44 cout << a[i] << " "; 45 cout << endl; 46 return 0; 47 }
标签:cout,int,void,namespace,5.12,template,setmember From: https://www.cnblogs.com/lijianlongCode13/p/17396448.html