[go: up one dir, main page]

0% found this document useful (0 votes)
63 views1 page

Templates in C++ Selection Sort Template

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++.
Copyright
© © All Rights Reserved
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as PDF, TXT or read online on Scribd
0% found this document useful (0 votes)
63 views1 page

Templates in C++ Selection Sort Template

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++.
Copyright
© © All Rights Reserved
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as PDF, TXT or read online on Scribd
You are on page 1/ 1

Templates in C++ Selection Sort Template

1. template <class T>


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;

You might also like