Array, using template <class>

I have to sort the 5 elements in a, the Days and the Vowels. How do I use the template <class T> with the way I put this??

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
 #include <iostream>
#include <algorithm>
#include <iomanip>

using namespace std;

// Function prototypes
 void DisplayA(int[], int);
 void showArray(int[], int);
 void DisplayB(string[], int);
 void showArrayDays(string[], int);

int main()
{
	int a[5] = { 10, 4, 9, 55, 11 };
	string Days[7] = { "Mon", "Tue", "Wed", "Thr", "Fri", "Sat", "Sun" };
	char Vowels[5] = { 'U', 'O', 'I', 'E', 'A' };

	cout << "Original array\n";
	cout << "a:   ";
	showArray(a, 5);
	
	cout << "Days: ";
	showArrayDays(Days, 7);

	// Sort the array
	DisplayA(a, 5);

	// Display the values again
	cout << "After being sorted\n";
	cout << "a:   "; 
	showArray(a, 5);


	system("pause");
	return 0;

}

void DisplayA(int array[], int size)
{
	int i, minIndex, minValue;
	for (i = 0; i < (size - 1); i++)
		{
		minIndex = i;
		minValue = array[i];
		for (int index = i + 1; index < size; index++)
		{
			if (array[index] < minValue)
				{
				 minValue = array[index];
				 minIndex = index;
				 }
			 }
		array[minIndex] = array[i];
		array[i] = minValue;
		 }
	
}

void showArray(int array[], int size)
{
	for (int count = 0; count < size; count++)
	cout << array[count] << " ";
	cout << endl;
}
Last edited on
Lets clarify: do you want to write two template functions, one for "sort" and other for "show" that you want to call with every array?
Assuming you want one templated function for show,

it would simply be what you already have, but you replace the types with T.
1
2
3
4
5
6
7
template <class T>
void showArray(T array[], int size)
{
	for (int count = 0; count < size; count++)
	    cout << array[count] << " ";
	cout << endl;
}

Now, the compiler will automatically handle any type of array you give it, assuming that the type has the << ostream operator (If you don't know what that means don't worry about it).

You should be able to apply the same thing to your "Display" function (which is a misleading name for a sort function, btw).
Last edited on
Topic archived. No new replies allowed.