C++练习 | 模板与泛式编程练习(1)
#include <iostream> #include <cmath> #include <cstring> #include <string> #include <iomanip> using namespace std; template<typename A> void Swap(A &t1,A &t2) { A t; t=t1; t1=t2; t2=t; } int main() { int a1, a2; double b1, b2; char c1 , c2 ; cin>>a1>>a2; cin>>b1>>b2; cin>>c1>>c2; Swap(a1,a2); cout<<a1<<","<<a2<<endl; Swap(b1,b2); cout<<b1<<","<<b2<<endl; Swap(c1,c2); cout<<c1<<","<<c2<<endl; return 0; }
交换函数,仅作格式记录。
#include <iostream> #include <cmath> #include <cstring> #include <string> #include <iomanip> using namespace std; template<typename A,size_t N> void input(A (&a)[N])//N即为数组长度 { for(size_t i=0;i!=N;i++) { cin>>a[i]; } } template<typename A,size_t N> void sort(A (&a)[N]) { sort(a,a+N); } template<typename A,size_t N> void output(A (&a)[N]) { for(int i=0;i<N;i++) { cout<<a[i]; if(i!=N-1) cout<<" "; else cout<<endl; } } int main() { int a1[4]; char a2[5]; double a3[6]; int type; while (cin >> type) { switch (type) { case 0: input(a1); sort(a1); output(a1); break; case 1: input(a2); sort(a2); output(a2); break; case 2: input(a3); sort(a3); output(a3); break; } } return 0; }
输入、排序和输出。