Write a program to sort array elements using a template.
#include<iostream> using namespace std; template <class T> class A { private: T a[5]; public: A(T x,T y,T z,T m,T n) { a[0] = x; a[1] = y; a[2] = z; a[3] = m; a[4] = n; cout << "parameterized constructor" << endl; } ~A() { cout << "destructor" << endl; } void sort_ascend() { int i,j; T temp; for(i = 0; i < 5;i++) { for(j = i + 1;j < 5;j++) { if(a[i] > a[j]) { temp = a[i]; a[i] = a[j]; a[j] = temp; } } } } void print() { for(int i = 0;i < 5;i++) { cout << a[i] << " "; } cout << endl; } }; int main() { A <int>ob1(23,54,45,8,33); A <char>ob2('M','A','G','I','C'); A <float>ob3(23.3,4.54,4.5,8.34,33.23); ob1.print(); ob1.sort_ascend(); ob1.print(); ob2.print(); ob2.sort_ascend(); ob2.print(); ob3.print(); ob3.sort_ascend(); ob3.print(); return 0; }
Output
parameterized constructor parameterized constructor parameterized constructor 23 54 45 8 33 8 23 33 45 54 M A G I C A C G I M 23.3 4.54 4.5 8.34 33.23 4.5 4.54 8.34 23.3 33.23 destructor destructor destructor