0 evaluări0% au considerat acest document util (0 voturi)
10 vizualizări1 pagină
This document discusses templates in C++. Templates allow functions and classes to be reused for different data types. A template function for selection sort is provided that uses a template type T to sort an array of any type. Examples are given of using templates with built-in types like int and with user-defined types like a Rectangle class. Templates promote code reuse in C++.
This document discusses templates in C++. Templates allow functions and classes to be reused for different data types. A template function for selection sort is provided that uses a template type T to sort an array of any type. Examples are given of using templates with built-in types like int and with user-defined types like a Rectangle class. Templates promote code reuse in C++.
This document discusses templates in C++. Templates allow functions and classes to be reused for different data types. A template function for selection sort is provided that uses a template type T to sort an array of any type. Examples are given of using templates with built-in types like int and with user-defined types like a Rectangle class. Templates promote code reuse in C++.
Template function in C++ makes it easier 2. void SelectionSort(T *a, const int n) float farray[100]; 3. {// sort a[0] to a[n-1] into nondecreasing to reuse classes and functions. order. int intarray[200]; .. A template can be viewed as a variable 4. for (int i = 0; i < n; i++) sort(farray, 100); that can be instantiated to any data type, 5. { sort(intarray, 200); 6. int j = i; irrespective of whether this data type is a 7. // find smallest integer in a[i] to a[n-1] fundamental C++ type or a user-defined 8. for (int k = i+1; k < n; k++) type. 9. if (a[k] < a[j]) {j = k;} 10. swap(a[i], a[j]); 11. } 12. } Program 3.1: Selection sort using templates
Program 3.4 Program 3.6
Class Bag Template <class T> { Class Bag public: { Bag(); public: ~Bag(); Bag(); ~Bag(); private: int *array; private: int capacity; T *array; int capacity; } }
Bag::~Bag(){delete array;} template <class T>
Bag<T>::~Bag(){delete array;} Declaration: Bag <int> a; Bag <Rectangle> a;